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 is called after the apex method execution gets completed in apex controller.

Some important points to note:

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

As an example, Let say In Javscirpt 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) {

}

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

Ex:

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

Point 3) action.setParams is the optional which is needed if we are expecting parameter in 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 result back from Apex controller method.

The apex method which return results are 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.

No comments:

Post a Comment