Lightning Component – Server Side Implementation in a Smart Way

For this training purpose, we are showing the contact records with respect to an account on the Account Lightning Record Page. We are using aura:iteration with html table for training purpose. Please use lightning base components such as lightning:dataTable in future.

Step 1: Create the Apex Class named “ShowContactsController”

ShowContactsController.apexc | To return all the associated Contact Records

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

public class ShowContactsController {
    
    @AuraEnabled
    public static List<Contact> getContactRecords(String accountId){
        
        List<Contact> contactList = [SELECT Id, Name, Account.Name, Owner.name, LastModifiedDate, CreatedBy.Name FROM Contact WHERE Account.Id =: accountId ORDER BY LastModifiedDate Desc];
        if(contactList <> NULL && contactList.size()>0)
        	return contactList;
        else
            return NULL;
    }

}
  • Lightning Components will understand only methods with @AuraEnabled annotation in Apex Class.
  • Apex Methods must be static and access specifier should be public or  global for Lightning Component’s communication.

Step 2:  Create a lightning component bundle named “showContacts”.

showContacts.cmp | to show the associated Contact Records [you can use lightning:dataTable]

<!-- @name: showContacts
 	 @description: to show the contact records with respect to Account-->

<aura:component implements="flexipage:availableforAllPageTypes,force:hasRecordId" controller="ShowContactsController">
    
    <aura:attribute name="contactList" type="List" description="contains Contact records"/>    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <table class="slds-table slds-table_fixed-layout slds-table_bordered">
        <thead>
            <tr class="slds-text-heading--label">                  
                <th scope="col" class="slds-cell-wrap" title="Name">
                    <div class="slds-truncate">Name</div>                      
                </th>
                <!--<th scope="col" class="slds-cell-wrap" title="Account Name">
                    <div class="slds-truncate">Account Name</div>                      
                </th>-->
                <th scope="col" class="slds-cell-wrap" title="Owner">
                    <div class="slds-truncate">Owner</div>                      
                </th>
                <th scope="col" class="slds-cell-wrap" title="Last Modified Date">
                    <div class="slds-truncate">Last Modified Date</div>                      
                </th>
                <th scope="col" class="slds-cell-wrap" title="Created By">
                    <div class="slds-truncate">Created By</div>                      
                </th>
            </tr>
        </thead> 
        <tbody>
            <aura:iteration items="{!v.contactList}" var="con">
                <tr>
                    <td class="slds-truncate" title="{!con.Name}">
                        <lightning:formattedText value="{!con.Name}"/>            
                    </td> 
                    <!--<td class="slds-truncate" title="{!con.Account.Name}">
                        <lightning:formattedText value="{!con.Account.Name}"/>            
                    </td>-->
                    <td class="slds-truncate" title="{!con.Owner.Name}">
                        <lightning:formattedText value="{!con.Owner.Name}"/>            
                    </td> 
                    <td class="slds-truncate" title="{!con.LastModifiedDate}">
                        <lightning:formattedDateTime value="{!con.LastModifiedDate}" year="2-digit" month="short" day="2-digit"/>            
                    </td> 
                    <td class="slds-truncate" title="{!con.CreatedBy.Name}">
                        <lightning:formattedText value="{!con.CreatedBy.Name}"/>            
                    </td> 
                </tr>
            </aura:iteration>
        </tbody>
    </table>   
</aura:component>

showContactsController.js | calling the helper function

/*controller.js*/
({
	doInit : function(component, event, helper) {
		helper.performShowingContacts(component, event);
	}
})

showContactsHelper.js | calling the Server Class and get the response from Server and set the respective return value

/*helper.js*/
({
    performShowingContacts : function(component) {
		var action = component.get("c.getContactRecords");
		this.setupPerformShowingContactsAction(component, action);
		$A.enqueueAction(action);
    },
    
    setupPerformShowingContactsAction : function(component, action) { 

		action.setParams({
			"accountId":component.get("v.recordId")
		});

		action.setCallback(this, function(response){
        	this.handlePerformShowingContactsResultsCallBack(component, response)
        });	
    },
    
    handlePerformShowingContactsResultsCallBack : function(component, response) {

		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))
                    component.set("v.contactList", responseValue);
                
                break;
                
            case 'INCOMPLETE': break;
			case 'ERROR': 
				console.log('Response Error-->'+JSON.stringify(responseError));
				break;
        }
        
    }
    
    
})


performShowingContacts:
This is responsible to call the specific method of Apex Class [Method Name: getContactRecords,  Class: ShowContactsController].
You can notice that we are calling the method by this syntax:  component.get(“c.getContactRecords”); And, $A.enqueueAction(action) is responsible to add the Server Side Action to the processing queue. Before going to this, the respective method named “setupPerformShowingContactsAction” is called.

setupPerformShowingContactsAction: This method is responsible to set the parameters in the respective method of the Apex Class.

      • In Apex Class: public static List<Contact> getContactRecords(String accountId)
      • In Helper: action.setParams({ “accountId“:component.get(“v.recordId”) });   // component.get(“v.recordId”) will return the current Account Record Id.

handlePerformShowingContactsResultsCallBack: action.setCallback() sets a callback action that is invoked after completion of server side actions. In this, method you will get the response state, response value as well as response errors.

There will be 5 types of responses.

      1. NEW – The action is created, but there is no progress yet
      2. RUNNING – The action is in progress.
      3. SUCCESS – The Action has been executed successfully.
      4. ERROR – The Server returned the error to Lightning Component
      5. INCOMPLETE – Component has not received the response. The Server might be down or Client is in offline mode.

After executed successfully, we have set the responseValue to contactList into the component. After that, component will iterate the contact list and will show the contact records.

Step 3: Place this Lightning Component into the Account Record Page.

 

Notes

  1. Calling server-side actions from Lightning Component are not counted against your organization’s API limits. However, all the Governor Limits in the Apex Class retain.
  2. The request payload limit of action.setParams() is 4 MB yet. So, please check the feasibility of  parameters in your apex class and js files of a Lightning Component.
  3. Always try to put the unique name of client-side and server-side actions in a component. For example, if we will write the function with same name such as “getContactRecords” in controller.js, it will call the function “getContactRecords” in controller.js instead of Calling Method of a Apex Class. May be, for that you can get error as in “unexpected execution process in infinite loop“.

 

9,479 total views, 3 views today

Rating: 5.0/5. From 2 votes.
Please wait...
This entry was posted in Lightning Components. Bookmark the permalink.

Leave a Reply