Lightning

Uses of Apex Controller with Lightning Component

Architect As A Service

Understanding:

In lightning, we use components to display data. Data can be anything ranging from the name of an sObject like Account to list of records of a particular sObject.

Now to get the data from salesforce, we need to make calls to the server using Javascript and Apex. The communication between lightning and apex works as follows:

Create an Apex Class

First, we need to create an apex class and a method that queries the data. After that, we return to the component controller. The apex class with name “contactListControllerApx ” is used to fetch the records is as shown:

Note: The method is preceded with @AuraEnabled notation which enables a method to be called from the component controller.

Connection between Lightning Component and Apex

Now to establish a connection between our Lightning Component and Apex. We need to specify the name of the Apex Class in the controller attribute of the Aura:component tag in the lightning component as shown below:

After that, we need to write the code in controller resource of the component. To fetch a data from Salesforce through Apex Controller.

The controller of the component is as shown:

The init method makes a call to the “getContactList” method of the Apex class, which returns the required list of contacts. We set a callback method to the call. After the request is returned this callback method is executed. In the callback method we check if the request executed successfully or not. So we get the response and check if it is “SUCCESS”. We could also incorporate logic with else part so that if the request returned an error then that part would be executed. After the list is obtained it is set into the attribute, which is then iterated over to display the records using iteration.

After that init method executes, the list is set to the records, then iterated over in the component using tag.

The list is displayed as shown:

Back to list

Leave a Reply

Your email address will not be published. Required fields are marked *