Lightning Aura method

In this blog, I am going to explain how to use the aura: method which allows you to directly call a method in a component’s client-side controller instead of firing and handling a component event.Here is the simple component “AuraMethod” which contains method “defaultParamers”  with the action called loadDefaultParams

<aura:component>
    <aura:handler name ="init" value="{!this}" action="{!c.doInit}"/>
    <aura:method name="defaultParamers" action="{!c.loadDefaultParams}">
        <aura:attribute type="String" name="header" default="Salesforce Header" />
        <aura:attribute type="String" name="footer" default="Salesforce Footer" />
        <aura:attribute type="String" name="title" default="Salesforce" />
    </aura:method>
    
</aura:component>

In the component controller doInit method I am calling the component  method with the name as shown below

        component.defaultParamers();

which hooks the loadDefaulParams method action to retrieve the values from the component action handler.

({
    doInit : function(component, event, helper) {
        component.defaultParamers();
    },
    loadDefaulParams : function(component, event, helper) {
        var params = event.getParam('arguments');
        console.log(params);
        if (params) {
            var title = params.title;
            var header = params.header;
            var footer = params.footer;
        }
    }
})

Calling Server Side Action

Now let’s consider the defaultParamers aura:method calls a server-side controller action to pass the method parameters. now server-side controller will return the result asynchronously so to handler the response we invoke the callback passed into the aura: method and set the result as a parameter in the callback.

 Define the apex class as shown below
public class AuraMethodController {
    @AuraEnabled
    public static List<String> getServerSideParams(){
        return new List<String>{'Salesforce header from Server' ,'Salesforce footer from Server' , 'Salesforce title from Server' };
    }    

}

Modify the component as shown below.

<aura:component controller="AuraMethodController">
    <aura:handler name ="init" value="{!this}" action="{!c.doInit}"/>
    <aura:method name="defaultParamers" action="{!c.loadDefaultParams}">
        <aura:attribute type="String" name="header" default="Salesforce Header" />
        <aura:attribute type="String" name="footer" default="Salesforce Footer" />
        <aura:attribute type="String" name="title" default="Salesforce" />
    </aura:method>
    
</aura:component>

Now in the controller, we have defined the “onSucess” callback function to handle the server side controller response. But in the below controller I am simply printing the server side response on callback function to console.

({
    doInit : function(component, event, helper) {
        component.defaultParamers();
    },
    loadDefaultParams : function(component, event, helper) {
        var params = event.getParam('arguments');
        var onSucess = function(result){
            console.log(result);
        }
        if (params) {
            onSucess;
        }
        var action = component.get("c.getServerSideParams");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                onSucess(response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    
})

Parent component to call a method on a child component

 aura: method is used to communicate down the containment hierarchy means from the parent component to child components.To communicate up the containment hierarchy, fire a component event in the child component and handle it in the parent component.Here are the child components

AuraMethod.cmp

<aura:component >
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:method name="defaultParamers" action="{!c.loadDefaultParams}">
        <aura:attribute type="String" name="header" default="Salesforce Header" />
        <aura:attribute type="String" name="footer" default="Salesforce Footer" />
        <aura:attribute type="String" name="title" default="Salesforce" />
    </aura:method>
    
</aura:component>
({
    doInit : function(component, event, helper) {
        component.defaultParamers();
    },
    loadDefaultParams : function(component, event, helper) {
        var params = event.getParam('arguments');
        if (params) {
            var title = params.title;
            var header = params.header;
            var footer = params.footer;
            console.log('title'+title)
        }
    },
    
})

Here is the below parent component which is used to pass the parent component data to the child component of the button click.

AuraMethodInvoke.cmp

<aura:component >
    <c:AuraMethod aura:id="child" />
    <aura:attribute name="header" type="String" default="Parent header"/>
    <aura:attribute name="title" type="String" default="Parent title"/>
    <aura:attribute name="footer" type="String" default="Parent footer"/>
    <lightning:button label="parent component to call a method on a child component"
                      onclick="{! c.callAuraMethod}" />
      
</aura:component>

 

({    
    callAuraMethod : function(component, event, helper) {
        var childCmp = component.find("child");
       var auraMethodResult = childCmp.defaultParamers(component.get('v.header') ,                                                       component.get('v.footer') ,                                                       component.get('v.title'));
     },
})

AuraMethodTest.app

<aura:application >
    <c:AuraMethodInvoke />
</aura:application>

when the user clicks on the parent component button which will get the data from the parent component attributes and pass it to the child component.

Method with Interface

Define the simple interface with the aura method as shown below.

AuraMethodIntf.intf

<aura:interface description="Interface template">
    
    <aura:method name="defaultParamers" action="{!c.loadDefaultParams}">
        <aura:attribute type="String" name="header" default="Salesforce Header" />
        <aura:attribute type="String" name="footer" default="Salesforce Footer" />
        <aura:attribute type="String" name="title" default="Salesforce" />
    </aura:method>
    
    
    
</aura:interface>

And then you can implement the interface as shown below.

<aura:component implements="c:AuraMethodIntf">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
</aura:component>
({
    doInit : function(component, event, helper) {
        component.defaultParamers();
    },
    loadDefaultParams : function(component, event, helper) {
        var params = event.getParam('arguments');
        if (params) {
            var title = params.title;
            var header = params.header;
            var footer = params.footer;
            console.log('title'+title);
            console.log('header'+header);
            
            console.log('footer'+footer);
            
        }
    },
    
})

 

 

 

 

Lightning Component Facets

In this blog post, I am going to explain salesforce lightning facets. lighting facets are nothing but attributes of type Aura.Component[] with the array of attributes like body, title etc.To define your own facet, add an aura:attribute tag of type Aura.Component[] to your component. The body attribute has type Aura.Component[] .Now to start with I created a new lighting component with name AuraFacet.cmp with below code.

<aura:component >
    <aura:attribute name="title" type="Aura.component[]" />
    <aura:attribute name="footer" type="Aura.component[]"/>
    <section>
        <div><span></span>{!v.title}</div>
        <div><span> </span>{!v.body}</div>
        <div><span></span>{!v.footer}</div>
    </section>
    
</aura:component>

This is the component which will have two attribute types title and footer facets that are passed from the invoked component.Now I created a component name facetwrapper.cmp with the below code.

<aura:component controller="FacetController">
    <aura:handler name="init" value="this" action="{!c.doInit}"/>
    <aura:attribute name="toggle" type="Boolean" default="true"/>
    <aura:attribute name="org" type="Organization" default=""/>
    
    <section>
        <aura:if isTrue="{!v.toggle}">
            <div>
                <div>
                    <c:AuraFacet aura:id="f1">
                        <aura:set attribute="title">
                            <ui:outputText value="Salesforce Lightning Component Title "/>
                        </aura:set>
                       
                         <aura:set attribute="body">
                            <ui:outputText value="Salesforce Lightning Component Body"/>
                        </aura:set>
                       
                        
                        <aura:set attribute="footer">
                            <p> Copyright 2017 @{!v.org.Name}  - {!v.org.Street} , {!v.org.City} ,{!v.org.State} ,{!v.org.Country} </p>
                             
                        </aura:set>
                        
                    </c:AuraFacet>
                </div>
                
            </div>
        </aura:if>
        <ui:button label="ToggleIf" press="{!c.toggle}" />
    </section>
</aura:component>

 

({
    doInit: function (cmp) {
        var action = cmp.get("c.getOrgDetails");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var resp = response.getReturnValue();
                cmp.set("v.org", resp);
            }
        });
        $A.enqueueAction(action);
        
        
    },
    toggle: function (cmp) {
        cmp.set('v.toggle', !cmp.get('v.toggle'));
    },
  
})

 

public class FacetController {
    @AuraEnabled
    public static Organization getOrgDetails(){
        return [Select Id , Name, Street , City , Country , PostalCode  from Organization] ; 
        
    } 
}

Now if you see the value of an attribute are passed by using the <aura:set> tag.Set tag is used to set the footer and body and title attributes from the wrapper component as shown below.

 

Lightning Application Events

Introduction

In this blog post, I am going to explain how to use the application events.Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All
components that provide a handler for the event are notified.But its good practice to use the component events whenever possible instead of application events.Create an application event contains there steps

Step 1: Create an Application event
Create a new application event with below code as shown below. appEvent.evt

<aura:event type="APPLICATION">
    <aura:attribute name="message" type="String"/>
</aura:event>

Step 2: Register an Event

A component registers that it may fire an application event by using <aura:registerEvent> in its markup. The name attribute is required but not used for application events. The name attribute is only relevant for component events. This example uses name=”</aura:appEvent” but the value isn’t used anywhere.

<aura:registerEvent name="appEvent" type="c:appEvent"/>

Step 3 : Fire an Event
Use $A.get(“e.myNamespace:myAppEvent”) in JavaScript to get an instance of the myAppEvent event in the myNamespace namespace.

var appEvent = $A.get("e.c:appEvent");
appEvent.setParams({ "myParam" : myValue });
appEvent.fire();

Put All together

Now lets put all together to understand the application events.Here below is the component which will trigger the application events.

AppNotifier.cmp

<aura:component>
    <b>  Notifer Component</b>
    <p> Please Enter the text and then Click here to fire button </p>
    <ui:inputText aura:id="inpId"  value="This is Really cool ..!" required="true"/>
    
    <aura:registerEvent name="appEvent" type="c:appEvent"/>
    <p><lightning:button
                         label="Click here to fire an application event"
                         onclick="{!c.fireApplicationEvent}" />
    </p>
</aura:component>

 

({
    fireApplicationEvent : function(cmp, event) {
        var appEvent = $A.get("e.c:appEvent");
        var inpText = cmp.find("inpId").get("v.value");
        appEvent.setParams({
            "message" :inpText  });
        appEvent.fire();
    }
})
.THIS{
    color: #2f5687;
    font-size:20px;
}

AppHandler.cmp

AppHandler is component that will handle the event notification which is fired from the AppNotifer component and handle them

<aura:component >
    <hr/>
    <b>  Handler Component</b>
    <aura:attribute name="messageFromEvent" type="String"/>
    <aura:handler event="c:appEvent" action="{!c.handleApplicationEvent}"/>
    <p>{!v.messageFromEvent}</p>
</aura:component>
({
    handleApplicationEvent : function(cmp, event) {
        var message = event.getParam("message");
        cmp.set("v.messageFromEvent", message);
            },
})
.THIS{
    color: #FF5733;
    font-size:20px;
}

AppContainer.cmp

<aura:component >
    <c:AppNotifier/>
    <c:AppHandler/>
    
</aura:component>

 

 

 

Lightning Component Events

Introduction

In this blog, I am going to explain salesforce lightning component events. The lightning component is event-driven framework model which control the flow determined by the occurrence of events from the notifier to the handler.The lightning framework supports two type of events namely component events and application events.A component event is fired from an instance of a component. A component event can be handled by the component that fired the event or by a component in the containment hierarchy that receives the event. Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component and all components that provide a handler for the event are notified.

Component Events

A component event is fired from an instance of a component. A component event can be handled by the component that fired the event or by a component in the containment hierarchy that receives the event.you can understand the component event in three steps . 1. Create Custome component event 2. Fire the Component event  3. Handle the component event

Step 1: Create Component Events
Create a custom component event name “CmpEvent.evt” as with below code.Events can contain attributes that can be set before the event is fired and read when the event is handled.

<aura:event type="Component" description="Event template" >
    <aura:attribute name="message" type="String"/>
</aura:event>

The component that fires an event can set the event’s data. To set the attribute values, call event.setParam() or event.setParams(). A parameter name set in the event must match the name attribute of a <aura:attribute> in the
event as shown below.

event.setParam("message", "event message here");

The component that handles an event can retrieve the event data. To retrieve the attribute value in this event, call event.getParam(“message”) in the handler’s client-side controller.

Step 2: Fire Component Events

Fire a component event to communicate data to another component. A component event can be handled by the component that fired the event or by a component in the containment hierarchy that receives the event.To fire the component event, you need to register the event first the need fire from the component.

<aura:registerEvent name="sampleComponentEvent" type="CmpEvent"/>

.Use fire() to fire the event from an instance of a component as shown below. get the register events from the controller call getEvent bypassing the register event name and fire the event by using event.fire() method .

var compEvent = cmp.getEvent("sampleComponentEvent");
compEvent.setParams({"message" : myValue });
compEvent.fire();

Step 3: Handling Component Events
A component event can be handled by the component that fired the event or by a component in the containment hierarchy that receives the event.
Use <aura:handler> in the markup of the handler component. For example:

<aura:handler name="sampleComponentEvent" event="CmpEvent"
action="{!c.handleComponentEvent}"/>

The name attribute in <aura:handler> must match the name attribute in the <aura:registerEvent> tag in the component that fires the event.
The action attribute of <aura:handler> sets the client-side controller action to handle the event. The event attribute specifies the event being handled.

Lets Put into Action 

So far we have seen how to setup and fire the component events steps. let’s put all into the actions now.Now create a new component Notifer.cmp will are used to register and fire the component event.

Notifer.cmp

<aura:component>
    <aura:registerEvent name="cmpEvent" type="c:CmpEvent"/>
    <lightning:button label="Click here to fire"
                      onclick="{!c.fireEvent}" />
</aura:component>
({
    fireEvent : function(cmp, event) {
        var cmpEvent = cmp.getEvent("cmpEvent");
        cmpEvent.setParams({
            "message" : "A component event fired At " + new Date()});
        cmpEvent.fire();
    }
})

Handler.cmp

Handler component is used to receive the events which are fired by notifier component and execute the corresponding action

<aura:component >
    <aura:attribute name="messageFromEvent" type="String" default="This Message is Replaced by Event Message after fire"/>
    <aura:handler name="cmpEvent" event="c:CmpEvent" action="{!c.handleComponentEvent}"/>
    <c:Notifier />
    <p>{!v.messageFromEvent}</p>
</aura:component>
({
    handleComponentEvent : function(component, event, helper) {
        var message = event.getParam("message");
        component.set("v.messageFromEvent", message);
    }
})

So for the notifier and handler component sends the event parameters from the predefined attribute values. Now, lets send event data from the input text to handler from the notifier  components .TO do that change the notifier component as shown below.

<aura:component >
    <br></br>
    <b> Please Enter the text and then Click here to fire button </b><br/>
    <ui:inputText aura:id="inpId"  value="This is Really cool ..!" required="true"/>
    <aura:registerEvent name="cmpEvent" type="c:CmpEvent"/>
    <lightning:button label="Click here to fire"
                      onclick="{!c.fireEvent}" />
</aura:component>
({
    fireEvent : function(cmp, event) {
        var cmpEvent = cmp.getEvent("cmpEvent");
        var inpText = cmp.find("inpId").get("v.value");
        cmpEvent.setParams({
            "message" : inpText});
        cmpEvent.fire();
    }
})

With the above change, you can enter the input text and pass it to the event params values from the entered text values from the notifier component  and same values is received in the handler component from the event params .