SalesforceBlue

Feel the rhythm of Salesforce

Aura

Aura Component Apex Controller Simplified

Aura Component Apex Controller acts as a server-side controller for your lightning component.

You can associate an apex class to act as a controller for your lightning component using the controller attribute.

Let’s modify the MyAwesomeAuraComponent which we have already created in the previous part to have its own Apex Controller.

Create an apex class name as MyAwesomeApexController and save the following code into it.

public with sharing class MyAwesomeApexController {

    @AuraEnabled
    public static String greetingsCall(String defaultMsg) {
        String welcomeMsg = ' Welcome to the learning journey of Salesforce Lightning Aura Components!';
        String userName = UserInfo.getFirstName();
        return defaultMsg + ' ' + userName + ', ' + welcomeMsg;
    }
}

In the above apex controller, we have annotated the method with @AuraEnabled annotation that will allow your controller method to be accessible from Aura Component.

A controller method that will be called from the aura component should be static, public, or global.

Let’s update the aura component. Please save the following code in the aura component – MyAwesomeAuraComponent

<aura:component controller="MyAwesomeApexController">
    <aura:attribute name="welcome" type="String" default="Hey" />

    <lightning:card title="AwesomeAuraComponent">
        <aura:set attribute="actions">
            <lightning:button label="Click Me!" onclick="{!c.greetings}"/>
        </aura:set>

        <p class="slds-p-horizontal_small">
            <p>{!v.welcome}</p>
        </p>
    </lightning:card>
</aura:component>	

Please save the following code in the following component javascript controller.

({
    greetings : function(component, event, helper) {

        var defaultMessage = component.get("v.welcome");

        var action = component.get("c.greetingsCall"); // referring to apex controller method.
        action.setParams({"defaultMsg":defaultMessage});

        action.setCallback(this, function (response) { 
            var state = response.getState();
            if (state === 'SUCCESS') {
                var result = response.getReturnValue();
                component.set('v.welcome', result); // setting attribute value with the fetched results.
                // Code when Success
            } else if (state === 'INCOMPLETE') {
                // Code when Imcomplete
            } else if (state === 'ERROR') {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + errors[0].message);
                    }
                } else {
                        console.log("Unknown error");
                }
            }
        });
        $A.enqueueAction(action); // Invoking the action
        
    }
})

In the above controller javascript, we make a server-side call to the apex method (server-side action).

Let’s split the above code into sub-segments to discuss it one by one.

var action = component.get("c.greetingsCall"); 

In the above code block, we are getting a reference to server-side action using –
component.get(“c.greetingsCall”).

c in component.get(“c.greetingsCall”) method refers to the apex controller which enables us to wire up the component javascript controller and apex controller.

action.setCallback(this, function (response) { 
    var state = response.getState();
    if (state === 'SUCCESS') {
        var result = response.getReturnValue();
        component.set('v.welcome', result); // setting attribute value with the fetched results.
        // Code when Success
    } else if (state === 'INCOMPLETE') {
        // Code when Imcomplete
    } else if (state === 'ERROR') {
        var errors = response.getError();
        if (errors) {
            if (errors[0] && errors[0].message) {
                console.log("Error message: " + errors[0].message);
            }
        } else {
                console.log("Unknown error");
        }
    }
});

In the above code block, action.setCallback(this, function (response){}) takes a callback function that is invoked when the server-side returns the response.

Based upon the state return by response.getState() in the callback function further actions are taken.

If the state is SUCCESS then we are setting the attribute with the value return from the server.

Any error that occurred on the server-side Apex, the state will be ERROR.

action.setParams({"defaultMsg":defaultMessage});

In the above code block, we are passing the parameters to the server-side action using action.setParams({“defaultMsg”:defaultMessage}).

It sets the value of the defaultMsg argument on the server-side controller’s greetingsCall method based on the welcome attribute value.

$A.enqueueAction(action);

In the above code block, $A.enqueueAction(action) adds the server-side controller action to the queue of actions to be executed.

Lighting Framework batches the actions in the queue into one server request and won’t be sending an individual request for each individual action.

The request payload includes all of the actions and their data serialized into JSON.

As of writing the request payload limit is 4 MB.

These actions are called asynchronously and once the action returns the response, the callback function will be invoked as described above.

For a server-side action call, all the governor limits followed by Apex classes will remain as it is.

You can preview the above aura component from an aura app to see it in action.

We have covered in the Aura Application how to preview an aura component.

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *