How to Implement a Lightning Component with Apex Controller

In this blog post, we will walk through the steps required to implement a Lightning Component that retrieves and displays a list of contacts from Salesforce using an Apex controller.

Step 1: Implement an Apex Controller

First, we need to create an Apex controller that will handle the server-side logic for fetching contacts. The following code defines a simple class named ContactsController:


public class ContactsController { @AuraEnabled public static List<Contact> getContacts() { return [SELECT Id, Name, Email FROM Contact ORDER BY CreatedDate ASC]; } }

Explanation:

  • The @AuraEnabled annotation makes the method accessible to Lightning Components.
  • The method getContacts performs a SOQL query to retrieve the contact records, sorting them by creation date in ascending order.

Step 2: Implement the JavaScript Controller

Next, we need to create the JavaScript controller for our Lightning Component. This controller will call the Apex method to fetch the contact list when the component initializes.


({ doInit: function(component, event, helper) { // Fetch the contact list from the Apex controller helper.getAllContacts(component); }, })

Explanation:

  • The doInit function is called when the component is initialized.
  • It uses the helper method getAllContacts to fetch the contacts from the server.

Step 3: Implement a JavaScript Helper

Finally, we need to implement a JavaScript helper that actually fetches the contacts from the Apex controller.


({ // Fetch the contacts from the Apex controller getAllContacts: function(component) { var action = component.get('c.getContacts'); // Set up the callback action.setCallback(this, function(actionResult) { component.set('v.contacts', actionResult.getReturnValue()); }); $A.enqueueAction(action); } })

Explanation:

  • The getAllContacts method retrieves the contacts using the Apex method getContacts.
  • A callback function is set up to handle the response, where the retrieved contacts are stored in the component's attribute v.contacts.
  • The $A.enqueueAction(action) line sends the action to the server for processing.

By following these steps, you have successfully implemented a Lightning Component that retrieves contacts from Salesforce using an Apex controller. This setup allows for efficient server communication and data handling in your Lightning applications.

Comments

Popular posts from this blog

Best Practices for Creating Salesforce Roll-Up Summary Triggers

CREATE WEB-FORM USING LIGHTNING WEB COMPONENTS SALESFORCE

Utilizing a Generic Pagination Class in Lightning Web Components - Part 1