Thursday, 30 August 2018

Invoke Apex from Lightning Component | how to call an Apex class from a Lightning component


In this post we will talk about how to call Apex class from Lightning Component.


Step 1) Create on Apex Class with @AuraEnabled annotation and method must be static.

public with sharing class UserController {
    @AuraEnabled
    public static List<User> getUserList() {
        return [Select id,name,email FROM User ];
    }
}

Step 2) Create Lightning Component with controller.
  • Add Controller attribute in <aura:Component tag to link the Apex Class like <aura:component controller="CLASSNAME">
  • Define <aura:Attribute tag to get value and to display value in Lightning page
  • Call Java Script doInit method to with <aura:handler" like <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

<aura:component controller="UserController">
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>   
    <aura:attribute name="userList" type="List" />
    <table class="slds-table slds-table_bordered slds-table_striped slds-table_cell-buffer slds-table_fixed-layout">
            <thead>
              <tr class="slds-text-heading_label">
                <th scope="col"><div class="slds-truncate" title="ID">ID</div></th>
                <th scope="col"><div class="slds-truncate" title="Name">Name</div></th>
                <th scope="col"><div class="slds-truncate" title="Type">Email</div></th>
              </tr>
            </thead>
            <tbody>
              <!-- Use the Apex model and controller to fetch server side data -->
              <aura:iteration items="{!v.userList}" var="usr">
                  <tr>
                      <th scope="row"><div class="slds-truncate" title="{!usr.Id}">{!usr.Id}</div></th>
                      <td><div class="slds-truncate" title="{!usr.Name}">{!usr.Name}}</div></td>
                      <td><div class="slds-truncate" title="{!usr.Email}">{!usr.Email}</div></td>
                  </tr>
              </aura:iteration>
            </tbody>
    </table>   
</aura:component>   



Step 3) In Java Script Controller method call the helper JS method like below
 
({
    doInit : function(component, event, helper) {
        helper.getUserList(component);
    },
})

Step 4) As per best practice use Helper method for all logic.
  • Call Apex Class method with component.get("c.getUserList");
  • Then Set the callback method in queue like action.setCallback(this, function(response) { ... });
  • If call is successful then set the result in <aura:Attribute like  component.set("v.userList", response.getReturnValue());

({
    getUserList : function(component) {
        var action = component.get("c.getUserList");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.userList", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        $A.enqueueAction(action);
    } ,

})

Step 5) Create one Application to test the result.

<aura:application extends="force:slds">
    <c:UserDetails />
</aura:application>   

Here is output.




Thanks
Amit Chaudhary

1 comment: