Salesforce Cookies #8

How to use namespace in managed lightning components

If you are working on a lightning component and it’s going to be a part of a managed package then you need to take care of namespace in client side JS code if you are accessing any custom field. This can be handled in various ways but I found one very quick way to handle this. Using wrapper could be a best way but it’s time consuming so you can use the following way.

Get the namesapce from server side controller and use that in the lightning components.

NamespaceDemoCompControllelr

public class NamespaceDemoCompController {   
    
    public NamespaceDemoCompController() {}
    
    @AuraEnabled
    public static String getNamespaceName() { 
        
        String nameSpacePrefix;
        ApexClass cs =[select NamespacePrefix from ApexClass where Name ='NamespaceDemoCompController'];
        if(cs.NamespacePrefix != null){
            nameSpacePrefix = cs.NamespacePrefix+'__';
        }
        else{
            nameSpacePrefix = '';
        }
        
        return nameSpacePrefix;
    }
    
    @AuraEnabled
    public static List<Expense__c> getExpenses() {
        
        return [SELECT Id,Name, Client__c, Date__c, Amount__c FROM Expense__c ];
    } 
}

NamespaceDemoComp

<aura:component controller="NamespaceDemoCompController" implements="force:appHostable,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
	<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="namespace" type="String"/>	
    <aura:attribute name="totalAmount" type="Decimal"/>
    Total Amount : {!v.totalAmount}
</aura:component>

NamespaceDemoCompController.js

({
    doInit : function(component, event, helper) {
    	//call apex class method
    	var action = component.get('c.getNamespaceName');
    	action.setCallback(this,function(response){
        	//store state of response
   			var state = response.getState();
        	if (state === "SUCCESS") {
       			//set response value in namespace attribute on component
				component.set('v.namespace', response.getReturnValue());
                helper.getTotalAmount( component );
        	}
        });
		$A.enqueueAction(action);
    },
    
})

NamespaceDemoCompHelper.js

({
  // Fetch the expenses from the Apex controller
  // Calculate total amount here, it's just for demo purpose where we can see the use of namespace
  getTotalAmount: function(component) {
    var action = component.get('c.getExpenses');

    // Set up the callback
    var self = this;
    action.setCallback(this, function(actionResult) {
        let expenseList = actionResult.getReturnValue();
        let totalAmount = 0;
        let namespace = component.get('v.namespace');
        for(let i=0; i<expenseList.length; i++ ) {
        	totalAmount += expenseList[i][namespace + 'Amount__c'];  
        }
        component.set('v.totalAmount', totalAmount);
    });
    $A.enqueueAction(action);
  }
})

 

So, you can see in the above example that using namespace in JS code can save lot of time as compared to wrapper classes. Expense__c is a custom object and this code will take care of the namespace automatically based on the running environment. If there is a namespace then it will be added as suffix with field’s API names in JS code.

Happy coding 🙂

Salesforce Cookies #7

Untitled

Calling a child lightning component method from the parent lightning component

When we have multiple nested components then we may run into a scenario in which our parent lightning component is supposed to call a method of its child component. This is a very common use case.


simplifies the code needed for a parent component to call a method on a child component that it contains

The lightning component framework has  which simplifies the code needed for a parent component to call a method on a child component that it contains. Following example states pretty everything you want to know about it.

Declare the method defination and it’s parameters in child component as explained below.

<aura:method name="handleShowHidePopupEvent" action="{!c.handleShowHidePopupEventAction}" description="Method to show or hide the popup from a button on the parent component">
    <aura:attribute name="showPopup" type="Boolean" default="true"/>
</aura:method>

Create a handler method in the client side controller of the same child component

({
   handleShowHidePopupEventAction : function(cmp, event) {
     var params = event.getParam('arguments');
     if (params) {
       var showPopup = params.showPopup;
       if(showPopup) {
         var cmpTarget = cmp.find('popupParentDiv');
         $A.util.removeClass(cmpTarget, 'slds-hide');
       } else {
         var cmpTarget = cmp.find('popupParentDiv');
         $A.util.addClass(cmpTarget, 'slds-hide');
       }
     }
   }
})

Above code snippet is toggling a parent div of the popup (model). You can also write any specific logic here which you just want to have in the child component only.

Calling method from the parent component – To close the popup after executing the save button logic or cancel button logic

<c:editRecordComponent aura:id="editRecordCmp"/>
<button class="slds-button" type="button" onclick="{!c.saveRecord}"> Save & Close </button>
<button class="slds-button" type="button" onclick="{!c.cancel}"> Cancel </button></pre>

Method in parent component controller

({
  cancel : function(cmp, helper, event){

    var editRecordCmp = component.find("editRecordCmp");
    editRecordCmp.handleShowHidePopupEvent( false );
  }
})

can also return a value once the execution has been completed.

To read more about, please check aura:method in Lightning Components Developer Guide.

Happy coding 🙂