Lightning Component for Communicating Server Side Aura Method – Best Practice 1

Poster 2 basic

Aura framework provides a javascript action function to send a request from the lightning component to apex controller and it returns the response back to the client side. Please refer this link to know how the server side action is handled by the client-side controller. In this blog we are explaining the best practices can be followed to do this communication.

Implementation

This implementation requires two components. The server communication is modularized into an abstracted component which is then extended to the second component as needed.

Abstract Component

<aura:component abstract="true" extensible="true" access="global" >
{!v.body}
</aura:component>

view raw
AbstractBase.cmp
hosted with ❤ by GitHub

({
runServerMethod : function (component, serverMethodName, successCallBack, failureCallback, params ) {
var self = this;
var action = component.get(serverMethodName);
if (params) {
action.setParams(params);
}
action.setCallback( this, function (response) {
var state = response.getState();
if (state === "SUCCESS") {
successCallBack.call(this,response);
} else if (state === "INCOMPLETE") {
// show a toast or create a callback to control this state as well.
console.log("Failed to connect Salesforce!!");
}else if (state === "ERROR") {
var errors = response.getError();
if (!errors) {
errors = [{"message" : "Unknown Error Occured"}];
}
failureCallback.call(this,errors);
}
});
$A.enqueueAction(action);
}
})

AbstractBase.cmp is the abstract component being extended to the ChildComponent. Please refer my old post which details how extending works in the lighting component.

  • runServerMethod – helper method defined in the AbstractBaseHelper.js file, to interact with the apex controller method.
  • Method Parameters 
    • component – default parameter in the js controller
    • serverMethodName – the name of the server method in the following format, namespace.method_name, eg: c.callApexControllerMethod
  • successCallBack – the callback executes for a successful server transaction
  • failureCallback – the callback executes for a failed transaction
  • params – parameters to be passed to the apex controller method.

response.getState() – provides the action status of the call happened from the client side to server side. The possible action states are NEW, RUNNING, SUCCESS, ERROR, INCOMPLETE and ABORTED.

Refer the link for more details: https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/controllers_server_actions_states.htm

You may have noticed that call method is invoked with two parameters in successCallback and failureCallback. The call is a seeded prototype method of vanilla javascript to invoke the function by passing the parameters. Please refer to the link given in the below reference section for details.

Sub Component

The ChildComponent is extended from the AbstractBase component so the subcomponent will have access to all the helper methods of the parent. The sub-component layout consists of input, checkbox and a button control. In addition to that, a couple of aura attributes are defined to store the values of the HTML controls and server responses.

c.sentMessage is a controller event which is triggered by the ‘send message’ button click which is used for invoking the helper method defined in the childComponent.

<aura:component extends="c:AbstractBase" controller="TestApexController">
<aura:attribute name="message" type="String" default=""/>
<aura:attribute name="serverMessage" type="String" default="" description="server message assigns to this"/>
<aura:attribute name="showError" type="Boolean" default="false" />
<aura:attribute name="showServerError" type="Boolean" default="false" />
<ui:inputText label="Message" value="{!v.message}" />
<lightning:input type="checkbox" label="Show Error" name="showErrorCheck" checked="{!v.showError}"/>
<lightning:button variant="brand" label="Send Message" onclick="{! c.sendMessage }" />
<br/><br/><br/>
<aura:if isTrue="{!v.showServerError}">
Server Message : {!v.serverMessage}
<aura:set attribute="else">
Server Message : {!v.serverMessage}
</aura:set>
</aura:if>
</aura:component>

view raw
ChildComponent.cmp
hosted with ❤ by GitHub

({
sendMessage : function(component, event, helper) {
helper.sendMessage(component,helper);
}
})

({
sendMessage : function (component,helper) {
var message = component.get("v.message");
var showError = component.get("v.showError");
var param = {"message":message,"showError":showError};
helper.runServerMethod(component,"c.callApexControllerMethod",function(response){
component.set("v.serverMessage",response.getReturnValue());
}, function(errors) {
component.set("v.showServerError",true);
component.set("v.serverMessage",errors[0].message);
},param);
console.log(message,showError);
}
})

The sendMessage method defined in the helper part of aura bundle is invoked from the controller part. The helper method calls the runServerMethod which is defined in the parent abstract component.

runServerMethod is invoked with the following parameters.

  • component
  • callApexControllerMethod – static method defined in the apex controller, TestApexController
  • success callback – sets the serverMessage attribute with the response message from the server.
  • failure callback – set the showServerError, serverMessage attributes with the server response.
  • param – Collection of input control values – {message:message,showError:showError};
    • message – the value of the input textbox
    • showError – checked or unchecked status as a boolean

TestApexController

The apex method mush have the following attributes.

  • static and public keywords
  • @AuraEnabled annotation
public class TestApexController {
@AuraEnabled
public static String callApexControllerMethod ( String message, Boolean showError ) {
String counterMessage = 'Response from apex controller – ' + 'Your Message : ' + message;
if (showError) {
throw new AuraHandledException('Custom Exception from the apex controller');
}
return counterMessage;
}
}

view raw
gistfile1.txt
hosted with ❤ by GitHub

The apex method accepts two parameters and returns a string message. The method throws an aura exception if the ‘showError’ parameter value is true

Testing Application

ChildComponent is invoked from the application markup.

<aura:application >
<c:ChildComponent />
</aura:application>

view raw
TestServerApp.app
hosted with ❤ by GitHub

Server communication Gif

Don’t forget to share the post if you like it & bookmark the blog for future references.

 

Poster 2 basic

Reference :

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/controllers_server_actions_call.htm

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

One thought on “Lightning Component for Communicating Server Side Aura Method – Best Practice 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s