journey2salesforce

How to use method in Lightning Component?

You can call a method using aura:method tag in a component’s client side controller instead of using Component Event.
In short,
aura:method communicates down the Containment Hierarchy that means a Parent Component can call aura:method on a child component in the same Containment Hierarchy. Communication Path: [Parent Component -> Child Component]

Component Event communicates up the Containment Hierarchy that means Child Component sends the message to Parent Component by Component Event. Communication Path: [Child Component -> Parent Component]

The communication for method is of two types:

1.Synchronous – Generally, a Synchronous method finishes executing before it returns. In this communication, this method will not be responsible to call Apex Class.

2. Asynchronous – Generally, Asynchronous code can continue to execute after return operation. In this communication, method is responsible to call Apex Class from javascript controller.

Now we will discuss about aura:method in detail.

Method Syntax

<aura:method name="invokeMethod" action="{!c.callAction}">
	<aura:attribute name="input1" type="String"/>
	<aura:attribute name="input2" type="String"/>
</aura:method>

Synchronous Communication

Defining Process

1. We will create Child Component bundle named “childMethodComponent” where aura:method will be defined.

childMethodComponent.cmp | defines the aura:method

<aura:component> 
    <aura:attribute name="message" type="String" description="This is used to hold the values sent by Parent Component"/>
    <aura:method name="invokeMethod" action="{!c.callAction}">
         <aura:attribute name="input1" type="String"/>
         <aura:attribute name="input2" type="String"/>
    </aura:method> 
    {!v.message}
</aura:component>

childMethodComponentController.js | defines the function(“callAction”) when method will be invoked

({
	callAction : function(component, event, helper) {
		var params = event.getParam('arguments');
		if (params) {
			var param1 = params.input1;
            var param2 = params.input2;
		}
        
        console.log("param1--->"+param1);
        console.log("param2--->"+param2);
        component.set("v.message",param1+'---'+param2);
    }
})

Calling Process

2. We will create Parent Component bundle named “parentMethodComponent” from where we will call the method of the child component.

parentMethodComponent.cmp | calling the child component named”childMethodComponent.cmp

<aura:component>
    <c:childMethodComponent aura:id="childComponentId"/>
    <lightning:button label="Call Method" onclick="{!c.callMethod}"/>
</aura:component>

parentMethodComponentController.js | calling the method(“invokeMethod“) of child component

({
	callMethod : function(component, event, helper) {
		var childComponentId = component.find("childComponentId");
        childComponentId.invokeMethod('a','b');
	}
})

So, we have learnt Method for Synchronous Communication. Now, we will focus on Method for Asynchronous Communication.

Asynchronous Communication

In this process, we will show the latest 5 Contact records in the Parent Component by calling the method of the Child Component.

1. In Asynchronous communication, we will get response from Server Side. So, we will create Apex Class named “ShowContactsController” to return latest 5 Contact records.

ShowContactsController.apxc | to return latest 5 Contact records by invoking method in javascript controller

/* @name: ShowContactsController 
   @description: return the latest 5 Contact Records*/

public class ShowContactsController {
    
    @AuraEnabled
	public static List<Contact> getContactRecords(){
        
        List<Contact> contactList = [SELECT Id, Name FROM Contact ORDER BY LastModifiedDate Desc LIMIT 5 ];
        if(contactList <> NULL && contactList.size()>0)
        	return contactList;
        else
            return NULL;
    }
}

2.Now, same components we will update for learning purpose.

childMethodComponent.cmp | defines the aura:method

<aura:component controller="ShowContactsController">	
    <aura:method name="invokeMethod" action="{!c.callAction}">
        <aura:attribute name="callback" type="Function"/>
    </aura:method>   
</aura:component>

Please notice that at Line No. 3, we have declared an attribute of type Function to callback.

childMethodComponentController.js | calling the helper.js with callback attribute

({
	callAction : function(component, event, helper) {
        var params = event.getParam('arguments');
        var callback;
        if (params)
            callback = params.callback;
        
		helper.performShowingContacts(component, callback);
    }
})

childMethodComponentHelper.js | to call the method named “getContactRecords” of the Apex Class “ShowContactsController”

({
      
    performShowingContacts : function(component, callback) {
        var action = component.get("c.getContactRecords");
        this.setupPerformShowingContactsAction(component, action, callback);
        $A.enqueueAction(action);
    },
     
    setupPerformShowingContactsAction : function(component, action, callback) { 
 
        action.setCallback(this, function(response){
            this.handlePerformShowingContactsResultsCallBack(component, response, callback);
        }); 
    },
     
    handlePerformShowingContactsResultsCallBack : function(component, response, callback) {
 
        var responseState = response.getState();
        var responseError = response.getError();
        var responseValue = response.getReturnValue();
 
        switch(responseState){
 
            default: break;
            case 'NEW': break;
            case 'RUNNING': break;
 
            case 'SUCCESS':
                 
                if(!$A.util.isEmpty(responseValue)){
                     if (callback) 
                         callback(response.getReturnValue());
                }
                 
                break;
                 
            case 'INCOMPLETE': break;
            case 'ERROR': 
                console.log('Response Error-->'+JSON.stringify(responseError));
                break;
        }
         
    }
   
})

Please notice that at Line No. 31-32, this Child Component returning the result from Server Side to Parent Component by calling “callback” function.

3. Need to update ParentMethodComponent.

parentMethodComponent.cmp | to show the latest 5 contact records

<aura:component>
    <aura:attribute name="contactList" type="List" description="This is used to store the Contact Records returned from Server Side"/>
    <c:ChildMethodComponent aura:id="childComponentId"/>    
 	
    <lightning:card>  
        <aura:set attribute="title">
            Contacts
        </aura:set>
        <aura:set attribute="actions">
            <lightning:button label="Show Contacts" onclick="{!c.callMethod}"/>
        </aura:set>
        <aura:if isTrue="{!v.contactList.length>0}">
            
        
        <div class="slds-m-left_medium">
            <aura:iteration items="{!v.contactList}" var="con">
                {!con.Name}
            </aura:iteration> 
        </div>


        </aura:if>
    </lightning:card>
</aura:component>

parentMethodComponentController.js | to invoke the Child Component’s method and set the List variable to the result returning from Child Component

({
	callMethod : function(component, event, helper) {
		var childComponentId = component.find("childComponentId");
        childComponentId.invokeMethod(function(result) {
            console.log("result: " + JSON.stringify(result));
            component.set("v.contactList", result);
        });
	}
})

Please notice that at Line No. 4-7, calling the method named “invokeMethod” of a child component and set the contactList to the result of contact records coming from Child Component via Method using Apex Class.

4. Result

Run the Lightning Component(parentMethodComponent.cmp) from Lightning Application for Learning Purpose. Otherwise, you can use of Lightning App Builder.

1,678 total views, 1 views today

Rating: 5.0/5. From 1 vote.
Please wait...

You may also like...