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 🙂