Salesforce: Helper Lightning Components

Helper Lightning Components, a name I came up with; or I’d like to think so. Regardless of who came up with the name, the idea still stands. I was working on a project and was thinking of creating a component that can serve as a library, or if you prefer, helper.

Now to give credit where it’s due, the idea came from ETLC_ApexBridge┬ácomponent. While working with ETLC_ApexBridge, I came across <aura:method>. Generally, controller methods for a component cannot be called from another component (let’s not talk about Inherited methods as that’s another discussion). But <aura:method> tag allows a developer to define a method; and parameters if needed. These methods call controller methods and can be used by other components; indirectly providing access to controller methods.

Enough talk, we will start looking at the code and that might give us a better understanding. Let’s start by creating a helper component.

<aura:component >
		Define whether to show logged messages or not.
  		This will allow to leave calls to functions intact but turn debug on/off as needed
    <aura:attribute name="debug" type="Boolean" default="false" />
	<aura:method name="log" action="{!c.log}" description="Method to log a message"> 
    	<aura:attribute name="message" type="String" default=""/> 
    log : function(cmp, event) {
        //Only use console.log if debug has been set to true
        if(cmp.get('v.debug') == false){
        //Get parameters sent to the method
        var params = event.getParam('arguments');
        if (params) {
            //Retrieve "message" param passed to this method and display it as an alert

Now that we have created the component, let’s use it by creating an app and calling this method from there.


<aura:application >
    <c:HelperCmp aura:id="HelperCmp" debug="true" />
    <ui:button label="Press Me" press="{!c.pressMe}" />
	pressMe : function(component, event, helper) {
		var HelperCmp = component.find('HelperCmp');
        HelperCmp.log('Button Clicked!');

Preview the app; We should now see a button. Clicking the button will raise an alert message!

That’s it! We have just created a helper. This can be expanded to include many capabilities. Some of those might be showToast or force:navigateToURL. Currently, these methods work in only. Using a helper, we can implement and standardize these for all of our components.

I’d be interested in learning if any of you have used this before and how. Or maybe how you plan to use it in future.

Leave a Reply