How to Call Server Side Apex Controller Action in Salesforce Lightning Component?

How to Call Server-Side Apex Controller Action from Client-Side Controller in Lightning Component?

Server-Side Controller method can be invoked by the client-side controller by using the value provider of c. Client-side action can also be invoked by using c syntax in the component markup.

In the component javascript controller cmp.get(“c.serverControllerMethod”) call invoke the 'serverControllerMethod' action of apex controller.

Parameters of server-side action can be set using the action.setParams() call.

Below snippet of code sets the value of parameter ‘firstParam’ on the server-side method:

action.setParams({ firstParam : cmp.get("v.firstParam")});

A callback action can also be invoked after the response has returned from the server, using the below snippet of code:

action.setCallback(this, function(response) { ... });

Here, the response parameter of the callback function has the response return by the server.

Server-side controller action can be added to the queue to actions to be executed using $A.enqueueAction(action). Enqueued actions will run at the end of the event loop. The lightning framework batches the enqueue action into a single request in spite of sending a separate request for every action. These actions execute asynchronously and have callbacks.

Let us understand the calling of server action from the client controller from an example:

Below is a snippet of code for Lightning Component Markup:

<aura:component controller="”myApexController”">
    <aura:handler name="”init”" value="”{!this}”" action="”{!c.callClient}”/"></aura:handler>
    <aura:attribute name="”myAttribute”" type="”String”" default="”Hello" world=""></aura:attribute>
</aura:component>

Here, in the component markup the handler of Init event calling the javascript action 'callClient';

Below is a snippet of code for Javascript Controller:

callClient : function(component, event, helper) { 
    var myAttribute = component.get("v.myAttribute"); // getting the value of component attribute using c notifier 
    var action = component.get("c.setAttribute"); // calling the server side action using c notifier 
    action.setParams({ "myString" : myAttribute }); // setting the arguments of server action 
    action.setCallback(this, function(response) { 
        var state = response.getState(); 
        if (state === “SUCCESS”) { 
            // Do stuff
        } 
        else { 
            console.log(state); 
        } 
    }); 
    $A.enqueueAction(action); 
}

Below is the snippet of code for Apex Controller:

@AuraEnabled // server side action should be auraEnabled 
public static void setAttribute(String myString) { 
    Account acc = new Account(); 
    Acc.name = myString; 
    Insert acc; 
}

Popular Salesforce Blogs