Saturday, September 30, 2017

Salesforce Lightning Events : Hands on Training Guide

In this blog, I am going to cover practice session to learn Salesforce Lightning Events concept. By end of this hands on training session, you will create an Lightning App which contains 2 different components and interacts between them by using Lightning events.

So lets get started.

Before starting this hands on training, set up you salesforce environment. Below are prerequisite for this session.
  • Sign up for Developer edition ( https://developer.salesforce.com/gettingstarted ) if you don’t have.
  • Enable My Domain in your org (Navigate to Set Up-My Domain).
  • After registering My Domain, deploy it for all users.
Create a Lightning Application:
  • In the Developer Console, choose File > New > Lightning Application.
  • Specify “ApplicationEventDemoApp” as the app name and click submit.
  • Specify below code in lightning app.
<aura:application extends="force:slds"> 
    <div class="slds-text-heading_large slds-text-align_center"> 
Application Event Demo App 
    </div> 
</aura:application>
  • Save the file.
  • Click  preview.

Upload Static Resource:
  • Download zip file from below URL:
  • Click on Setup > Static Resouce > New
  • Specify name as “LightningEventsResources” and browse zip file.
  • Specify “Public “ for Cache Control field and click on Save.

Create a IndependentHospital lightning Component
  • In the Developer Console, choose File > New > Lightning Component.
  • Specify “IndependentHospital” as the component name and click submit.
  • Specify below code in lightning component.
<aura:component > 
   <div class="slds-align--absolute-center"> 
       <b>Hospital Component</b> 
   </div> 
</aura:component>
  • Save the file.
  • Add this component in “ApplicationEventDemoApp” Lightning App and click on save and preview.
<aura:application extends="force:slds"> 
    <div class="slds-text-heading_large slds-text-align_center"> 
Application Event Demo App 
    </div> 
    <c:IndependentHospital/> 
</aura:application>

Let see what we have done !!!



Update the IndependentHospital lightning Component with below code
  • Update the IndependentHospital component with below code to add some action to send ambulance.
<aura:component >
    <aura:attribute name="msgFromNotifier" type="String" default=""/>
    <div class="slds-card">
        <div class="slds-card__header slds-grid">
            <header class="slds-media slds-media_center slds-has-flexi-truncate">
                <div class="slds-media__figure">
                    <img src="{!$Resource.LightningEventsResources  + '/resources/hospitalImage.jpg'}" height="100" width="100"/>
                </div>
                <div class="slds-media__body">
                    <h2>
                        <a href="javascript:void(0);" class="slds-card__header-link slds-truncate" >
                            <span class="slds-text-heading_small">Hospital</span>
                        </a>
                    </h2>
                </div>
            </header>
            <div class="slds-no-flex">
                <lightning:button label="Reset" variant="brand" onclick="{!c.resetComponent}"/>
                <lightning:button label="Send Ambulance" variant="brand" onclick="{!c.sendAmbulanceMannually}"/>
            </div>
        </div>
        <div class="slds-card__body slds-card__body_inner">
            <div class="{!if(v.msgFromNotifier == '', 'slds-show','slds-hide')}">
                <div class="slds-align--absolute-center">
                    <b>Waiting for instructions</b>
                </div>
                <div class="slds-align--absolute-center">
                    <img src="{!$Resource.LightningEventsResources  + '/resources/staticAmbulance.jpg'}" height="256" width="200"/>
                </div>
            </div>
           <div class="{!if(v.msgFromNotifier == '', 'slds-hide','slds-show')}">
                <div class="slds-align--absolute-center">
                    <b> Message from Notifier : {!v.msgFromNotifier}</b>
                </div>
                <div class="slds-align--absolute-center">
                    <img src="{!$Resource.LightningEventsResources  + '/resources/animatedAmbulance.gif'}"/>
                    <audio  controls="controls" aura:id="audioclip" class="slds-hide"/>
                </div>
            </div>
        </div>
        <footer class="slds-card__footer">@sunil02kumar</footer>
    </div>
    
</aura:component>


  • Click HELPER in the right side bar of the code editor and replace code with below code and save the file.
({ 
     PlayAmbulanceSiren : function(component) { 
var rUrl = $A.get('$Resource.LightningEventsResources'); rUrl = rUrl + '/resources/ambulanceSiren.mp3'; 
console.log(rUrl); 
var domElement = component.find("audioclip").getElement(); domElement.src=rUrl; 
domElement.play(); 
      } 
})
  • Click CONTROLLER in the right side bar of the code editor and replace code with below code and save the file.
({
    sendAmbulanceMannually: function(component, event, helper) {
        component.set("v.msgFromNotifier", "sending ambulance mannually");
        helper.PlayAmbulanceSiren(component);
    },
    resetComponent :function(component, event,helper){
        component.set("v.msgFromNotifier", "");
    }
})


Create a IndependentCarAccidentNotifier lightning Component
  • In the Developer Console, choose File > New > Lightning Component.
  • Specify “IndependentCarAccidentNotifier” as the component name and click submit.
  • Specify below code in lightning component and save file.
<aura:component >
    <div class="slds-card">
        <div class="slds-card__header slds-grid">
            <header class="slds-media slds-media_center slds-has-flexi-truncate">
<div class="slds-media__body">
                    <h2>
       <a href="javascript:void(0);" ><span class="slds-text-heading_small">Car Accident Notifier </span> <a>
                    </h2>
                </div>
            </header>
            <div class="slds-no-flex">
                <lightning:button label="Send Notification via App Events " variant="brand"/>
            </div>
        </div>
        <div class="slds-card__body slds-card__body_inner">
            <div class="slds-align--absolute-center">
                <img src="{!$Resource.LightningEventsResources  + '/resources/accident.jpg'}" height="256" width="200"/>
            </div>
        </div>
        <footer class="slds-card__footer">@sunil02kumar</footer>
    </div>
</aura:component>



Modify Lightning Application
  • Modify the in “ApplicationEventDemoApp” Lightning App code and click on save and preview.
<aura:applicationextends="force:slds">
<div class="slds-text-heading_largeslds-text-align_center">
Application Event Demo App
</div>
<c:IndependentHospital/>
<c:IndependentCarAccidentNotifier/>
</aura:application>


Lets see what we have done!!


Create a carAccidentAppEvent lightning Event
  • In the Developer Console, choose File > New > Lightning Event.
  • Specify “carAccidentAppEvent” as the event name and click submit.
  • Specify below code in lightning event and save file.
<aura:event type="APPLICATION" description="Event template" >
<aura:attribute name="msg" type="String" access="GLOBAL"/> 
</aura:event>


Register for event in IndependentCarAccidentNotifier Component
  • Register for event in IndependentCarAccidentNotifier Component
<aura:registerEvent name="carAccidentAppEvent" type="c:carAccidentAppEvent"/>
  • Click CONTROLLER in the right side bar of the code editor and replace code with below code and save the file.
({
    fireCarAccidentAppEvent : function(component, event, helper) {                                                   console.log('fireCarAccidentAppEvent is called');
//syntax for app event
var appEvent = $A.get("e.c:carAccidentAppEvent");
appEvent.setParams({"msg":"Car Accident Notification through Application event. Sending ambulance!!!."});
appEvent.fire();
    }
})
  • Call this javascript function on button click.
<lightning:button label="Send Notification via App Events " variant="brand" onclick="{!c.fireCarAccidentAppEvent}"/>


Handle Event in IndependentHospital Component
  • Write Event handler in hospital component. Add below code in IndependentHospital component.
<aura:handler event="c:carAccidentAppEvent" action="{!c.handleNotification}"/>
  • Create an attribute to store msg send by event.
<aura:attribute name="msgFromNotifier" type="String" default=""/>
  • Click CONTROLLER in the right side bar of the code editor and replace code with below code and save the file.
handleNotification : function(component, event, helper){ 

console.log('handleNotification is called'); 

var sentMessage= event.getParam("msg"); 

console.log('******sentMessage by app event:'+sentMessage);

component.set("v.msgFromNotifier", sentMessage);
helper.PlayAmbulanceSiren(component); 
}

Lets see what we have done!!!

Now preview the Lightning app and click on "Send notification vai App Events" button which will trigger ambulance in independentHospital component.



So after completing this, you will understand the concept of communication between 2 different components by using application events.

Hope this will help!!!





1 comment: