How to pass data from parent component to child component Using Application event in salesforce | How to Use Application Event to pass attribute value from one lightning component to another in aura lightning component Salesforce

1,727 views

Hey guys, today in this post we are going to learn about How to Use Application Event to pass attribute value from one lightning component to another in aura lightning component Salesforce.

Event-driven programming is used in many languages and frameworks, such as JavaScript and Java Swing. The idea is that you write handlers that respond to interface events as they occur.

A component registers that it may fire an event in its markup. Events are fired from JavaScript controller actions that are typically triggered by a user interacting with the user interface.

Challenges in your career

đŸŽ¯ If You Are Facing Any Of These 6 Challenges in your career.

  • Learn Salesforce Development
  • Career Confusion
  • No Interview Call
  • Low Salary
  • No Promotion/Growth
  • No Finding New Job Opportunity
  • Why you stucking from past so many years in same company?

 

There are two types of events in the framework:

  • Component events are handled by the component itself or a component that instantiates or contains the component.
  • Application events are handled by all components that are listening to the event. These events are essentially a traditional publish-subscribe model. To know more details about Events, Clcick Here.

 

Files we used to Application event in Lightning Component →

appEventCmp.cmp Lightning Component It is used to click function to display record based on record Id.
appEventCmpController.js JavaScript Controller It is hold Javascript findAccDetail fnction to connect javascript controller to helper function.
appEventCmpHelper.js JavaScript Controller Helper It is hold Javascript recordAccData function to get the record based on record Id and pass the attribute event value.
AccountDetailsCmp.cmp Lightning Component It is child component and iterating data from salesforce object.
AccountDetailsCmpController.js JavaScript Controller It is hold Javascript storeEventData fnction to connect javascript helper function.
AccountDetailsCmpHelper.js JavaScript Controller Helper It is hold Javascript storeEventData fnction and get event value that is coming from parent component.
accountEventCtrl.apxc Apex Class Controller It is used to get Account Record based on Record Id in Apex Method.
myAppEvent.evt Lightning Event It is used to store the attributes value and pass from parent to child component through javascript register/handler Event in component.

 

Final Output →

application event in aura lightning -- w3web.net

 

You can download file directly from github by Click Here.

 

Other related post that would you like to learn in Salesforce

 

  • Find the below steps ▾

 

Create Lightning Component

Step 1:- Create Lightning Component : appEventCmp.cmp

From Developer Console >> File >> New >> Lightning Component

appEventCmp.cmp [Lightning Component File]


  1.    <aura:component controller="accountEventCtrl" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
  2. 	<aura:registerEvent name="regAppEvent" type="c:myAppEvent"/> 
  3.     <aura:attribute name="isLoading" type="Boolean" default="false"/>
  4.     <aura:attribute name="showAccDetails" type="boolean"/>
  5.  
  6.     <div class="slds slds-p-around_medium">
  7.  
  8.         <lightning:card title="{!v.headerTitle}">
  9.         <aura:set attribute="actions">
  10.             <lightning:button variant="Neutral" label="Account Detail" onclick="{!c.findAccDetail}"></lightning:button>    
  11.         </aura:set>
  12.     </lightning:card>
  13.  
  14.  
  15.     <aura:if isTrue="{!v.showAccDetails}">
  16.         <div class="slds-modal slds-fade-in-open slds-modal_large">
  17.             <div class="slds-modal__container">
  18.                 <header class="slds-modal__header">
  19.                     <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close">
  20.                         <span class="slds-assistive-text">Close</span>
  21.                     </button>
  22.                     <h2 id="modal-heading-01" class="slds-modal__title slds-hyphenate">Account Details</h2>
  23.                 </header>
  24.  
  25.                 <div class="slds-modal__content slds-p-around--medium slds-grid slds-wrap " style="height:500px;">
  26.                     <c:AccountDetailsCmp />
  27.                 </div>
  28.                 <footer class="slds-modal__footer">
  29.                     <button class="slds-button slds-button_neutral" onclick="{!c.closeModal}">Close</button>
  30.                 </footer>
  31.             </div>
  32.         </div>
  33.         <div class="slds-backdrop slds-backdrop_open"></div>
  34.     </aura:if>
  35.     <aura:if isTrue="{! v.isLoading }">
  36.         <lightning:spinner alternativeText="Loading"/>
  37.     </aura:if>
  38.     </div>
  39.  
  40. </aura:component>

 

Create JavaScript Controller

Step 2:- Create Lightning Component : appEventCmpController.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Controller

appEventCmpController.js [JavaScript Controller]


  1.    ({
  2. 	findAccDetail : function(component, event, helper) {
  3. 	  helper.recordAccData(component, event, helper);
  4. 	},
  5.  
  6.     closeModal : function(component, event, helper){
  7.         component.set("v.showAccDetails", false);
  8.     },
  9. })

 

Create JavaScript Helper

Step 3:- Create Lightning Component : appEventCmpHelper.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Helper

appEventCmpHelper.js [JavaScript Helper File]


  1.    ({
  2.  
  3. 	recordAccData : function(component, event, helper) {
  4.         component.set("v.showAccDetails", true);
  5.         var rcordId = component.get("v.recordId");       
  6.         var action = component.get("c.accItemList");
  7.         component.set("v.showAccDetails", true);
  8.          action.setParams({
  9.             "recId" : rcordId
  10.         });
  11.         action.setCallback(this, function(response){
  12.             var state = response.getState();
  13.              console.log('state', state);
  14.             if(state = "SUCCESS"){
  15.                 var result = response.getReturnValue();   
  16.                 //alert('result111 ' + JSON.stringify(result));
  17.                 //console.log('result222 ' + JSON.stringify(response.getReturnValue()));
  18.  
  19.                 var appEvent = $A.get("e.c:myAppEvent");
  20.                 appEvent.setParams({
  21.                     "accItemEvntData":result,
  22.                     "accID" :rcordId
  23.                 });
  24.                 appEvent.fire();
  25.             }
  26.         });
  27.         $A.enqueueAction(action);
  28. 	},
  29.  
  30. })

 

Create Lightning Component

Step 4:- Create Lightning Component : AccountDetailsCmp.cmp

From Developer Console >> File >> New >> Lightning Component

AccountDetailsCmp.cmp [Lightning Component File]


  1.    <aura:component controller="accountEventCtrl" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
  2. 	<aura:handler name="init" value="{!this}" action="{!c.doInit}" />    
  3.     <aura:attribute name="accListItem" type="List"/>
  4.     <aura:handler event="c:myAppEvent"  action="{!c.storeEventData}"/>	    
  5.     <aura:attribute name="accID" type="string"/>    
  6.  
  7.  
  8.     <div class="slds slds-p-around_medium">
  9.  
  10.         <table class="slds-table slds-table--bordered slds-table--fixed-layout slds-max-Large-table--stacked-horizontal" >
  11.           <thead>
  12.                <tr class="slds-line-height_reset">
  13.                    <th>Name</th>
  14.                    <th>Phone</th>
  15.                    <th>Industry</th>
  16.                    <th>Type</th>
  17.                    <th>Description</th>
  18.                </tr>
  19.           </thead>
  20.            <tbody>
  21.               <aura:iteration items="{!v.accListItem}" var="item" indexVar="index"> 
  22.                <tr>
  23.                    <td><div class="slds-truncate slds-line-clamp" title="{!item.Name}">{!item.Name}</div></td>
  24.                    <td><div class="slds-truncate slds-line-clamp" title="{!item.Name}">{!item.Phone}</div></td>
  25.                    <td><div class="slds-truncate slds-line-clamp" title="{!item.Name}">{!item.Industry}</div></td>
  26.                    <td><div class="slds-truncate slds-line-clamp" title="{!item.Name}">{!item.Type}</div></td>
  27.                    <td><div class="slds-truncate slds-line-clamp" title="{!item.Name}">{!item.Description}</div></td>
  28.                </tr>
  29.  
  30.               </aura:iteration>     
  31.            </tbody> 
  32.         </table>   
  33.     </div>
  34.  
  35. </aura:component>

 

Create JavaScript Controller

Step 5:- Create Lightning Component : AccountDetailsCmpController.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Controller

AccountDetailsCmpController.js [JavaScript Controller]


  1.   ({
  2.     doInit : function(component, event, helper) {
  3.     },
  4.  
  5.     storeEventData : function(component, event, helper) {       
  6.        helper.storeEventDataHelper(component, event, helper);
  7.     },
  8.  
  9. })

 

Create JavaScript Helper

Step 6:- Create Lightning Component : AccountDetailsCmpHelper.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Helper

AccountDetailsCmpHelper.js [JavaScript Helper File]


  1.    ({
  2. 	storeEventDataHelper : function(component, event, helper) {       
  3.          var accItemEvntData = event.getParam("accItemEvntData");
  4.          var accID = event.getParam("accID");    
  5.  
  6.          component.set("v.accListItem", accItemEvntData);
  7.          component.set("v.accID", accID);
  8.  
  9.     },
  10.  
  11. })

 

Create Lightning Event

Step 7:- Create Lightning Event : myAppEvent.evt

From Developer Console >> File >> New >> Lightning Event

myAppEvent.evt [Lightning Event File]


  1.    <aura:event type="APPLICATION" description="Event template">
  2.     <aura:attribute name="accItemEvntData" type="accountEventCtrl[]"/>
  3.     <aura:attribute name="accID" type="String"/>
  4. </aura:event>

 

Create Apex Class Controller

Step 8:- Create Apex Class : accountEventCtrl.apxc

From Developer Console >> File >> New >> Apex Class

accountEventCtrl.apxc [Apex Class Controller]


  1.   public class accountEventCtrl {
  2.  
  3.   @AuraEnabled
  4.     public static List<Account> accItemList( Id recId){
  5.         List<Account> accObj = [SELECT Id, Name, Phone, Industry, TYPE, Description FROM Account WHERE Id=:recId];
  6.         system.debug('accObj ' + accObj);
  7.         RETURN accObj;
  8.     }  
  9.  
  10. }

 

Further post that would you like to learn in Salesforce

 


 

FAQ (Frequently Asked Questions)

What is event propagation in Aura component?

What is event propagation in Aura component? Image result for event propagation in aura Event propagation determines how you communicate in your application. The event propagation rules determine which components in the containment hierarchy can handle events in the bubble or capture phase. The framework supports capture and bubble phases for component event propagation.

How do you stop event propagation in Aura component?

Any handling event can stop propagation by calling stopPropagation() on the event. Bubble phase :-The framework executes the bubble phase from the source component to the application root until all components are traversed or stopPropagation() is called.

What are the three phases of event propagation in JS?

There are three different phases during lifecycle of an JavaScript event. They follow the same order as listed above. Capturing Phase is when event goes down to the element. Target phase is when event reach the element and Bubbling phase is when the event bubbles up from the element.

Related Topics | You May Also Like

 
  

Our Free Courses →

👉 Get Free Course →

📌 Salesforce Administrators

📌 Salesforce Lightning Flow Builder

📌 Salesforce Record Trigger Flow Builder

👉 Get Free Course →

📌 Aura Lightning Framework

📌 Lightning Web Component (LWC)

📌 Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment