Friday, May 17, 2019

Calling a Server-Side Action

When we call a server-side controller i.e (Apex controller) method from a client-side controller i.e (Javascript controller), Apex controller method return results. In the javascript controller, We use action.setCallback which runs after the apex method execution gets completed in the apex controller.

Some important points to note:

Point 1) In the javascript controller, we use the value provider 'c' to invoke an Apex controller action.

As an example, Let say in the Javascript controller we have action findAccount from where we are calling fetchAccount method of apex controller.

Javascript Controller,

({
 findAccount : function(component, event, helper) {
var action=component.get('c.fetchAccount');  //  using c to call Apex controller method
}

Apex controller,


public static List < account > fetchAccount(String searchKeyWord) {
// Some operations
}

Point 2)  We also use the value provider 'c'  in component markup to invoke a javascript controller action.

Example:

<lightning:button label="Search Account" onclick="{!c.findAccount}" />
// Calling javascript controller action on button click.

Point 3) action.setParams is optional which is needed if we are expecting parameter in the apex controller method.


Javascript controller,

({
 findAccount : function(component, event, helper) {
        var action=component.get('c.fetchAccount');
        action.setParams({
            searchKeyWord : component.get("v.keywordHolder") // Use Exact keyword used in apex controller method
        });
}
})

Apex controller,


public static List < account > fetchAccount(String searchKeyWord) {
}

Point 4) Getting results back from the Apex controller method.

The apex method which returns results is available in the response variable, which is the argument of the action.setCallback.

The method used with response are,

response.getState() // Get the state of action return from server.

response.getReturnValue() // Get the values.

Point 5) 

$A.enqueueAction(action) adds the server-side controller action to the queue of actions to be executed.The actions are asynchronous and have callbacks.

8 comments: