Browsing "Older Posts"

Browsing Category "Lightning Components"
  • How to pass values from child to parent lightning aura component with Component Event

    salesforcepoint Wednesday, 23 December 2020

     How to pass  Data from child lightning aura component to parent lightning aura component & Fire Parent component function from child component function

    How to Pass Data From Child Lightning Aura Component to Parent Lightning Aura Component


    If we need to pass values from child aura component to parent, we can't pass directly, for that we need to create custom lightning event.

    Steps for child to parent aura component communication:
     1. First we need to create custom Component event with required attributes (for passing values from child to parent). eg: compEvent

    2. We need to register event on child component using  <aura:registerEvent>.
    examle:
    <aura:registerEvent name="sampleComponentEvent" type="c:compEvent"/>

    3. Fire an Event: Fire an Event when some event occurs on child component(Eg: Button onclick, onchange of Input Text...).
    Example:
    var compEvent = component.getEvent("sampleComponentEvent");
             compEvent.setParams({"message" : "Static Text" });
             compEvent.fire();

    4. We need to handle event on Parent Component. Handler name and registerEvent name should be same. We can invoke function with the help of "action" attribute.
    Example:
        <aura:handler name="sampleComponentEvent" event="c:compEvent"
            action="{!c.handleComponentEvent}"/>

    When the child function gets fired, it calls custom event and pass required parameter’s. After that event invokes Handler method on Parent component(Eg: handleComponentEvent). By using " event.getParam("eventAttributeName"); " we can retrieve values that are passed to custom event.

    Example: Fire Parent Lightning Aura Component function from Child component and pass parameters.

    compEvent (component Event):
    <aura:event type="COMPONENT">
        <aura:attribute name="message" type="String"/>
    </aura:event>

    childComponentCmp
    
      <aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome" access="global" >
        <aura:attribute name="enteredText" type="String"/>
        <aura:registerEvent name="sampleComponentEvent" type="c:compEvent"/>
        
        <div class="slds-box slds-p-around_medium">
            <h2>This is Child Component</h2>
            <lightning:input label="Enter Name" aura:id="name" value ="{!v.enteredText}" />
            <lightning:button class="slds-m-top_small" variant="brand" label="Pass Value To Parent" title="Click Here" onclick="{! c.handleClick }"/>
        </div>
    </aura:component>
      

    childComponentCmpController.js
    
      ({
        handleClick : function(component, event, helper) {
            var compEvent = component.getEvent("sampleComponentEvent");
            compEvent.setParams({
                "message" : component.get("v.enteredText") 
            });
            compEvent.fire();
        }
    })
      

    ParentComponentCmp
    
      <aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome" access="global" >
        <aura:attribute name="enteredValue" type="String" />
        <aura:handler name="sampleComponentEvent" event="c:compEvent" action="{!c.handleComponentEvent}"/>
        
        <c:childComponentCmp/><br /><br />
        <div class="slds-box slds-p-around_medium">
            <h2>This is Parent Component</h2>
            value entered on child component input Box: <b>{!v.enteredValue}</b>
        </div>
    </aura:component>
      

    ParentComponentCmpController.js
    
      ({
        handleComponentEvent : function(component, event, helper) {
            var valueFromChild = event.getParam("message");
            alert(valueFromChild)
            component.set("v.enteredValue", valueFromChild);
        }
    })
      

    Output

  • How To Get Record Id From aura:iteration In Lightning Component

    salesforcepoint Sunday, 26 July 2020

    Fetch Selected Record Id From Iteration Lightning Aura Component:




    If we need to fetch record id or some element from aura:iteration we can use html property dataset. By using this html dataset attributes we can pass id from component to JavaScript function when some event occurs. The name of a custom data element starts with data-. By using html elements, we can get not only id but we can get any element that we set for data element (ex: data-id, data-name) in lightning component.

    Example code for fetching record id in aura iteration:

    In below example we are fetching all the student records, In aura iteration  for div element we added data-id ="{!student.Id}". on click on student we are passing selected student id to JavaScript function handleSelect by using event.target.dataset.id. If we need to pass other attribute then we can create new data attribute, for example if we need to pass name of selected student then we add new attribute data-name and in js function we can get that attribute by using event.target.dataset.name.

    StudentController.cls
     public class StudentController {  
       @AuraEnabled  
       public static List<Student__c> getStudentList() {  
         List<Student__c> studentList = [SELECT Id, Name FROM Student__c];  
         return studentList;  
       }  
     }  
    

    StudentList.cmp
     <aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,  
                   flexipage:availableForRecordHome,force:hasRecordId,  
                   force:lightningQuickAction" controller="StudentController"  
             access="global" >  
       <aura:attribute name="studentList" type="List" />  
       <aura:handler name="init" action="{!c.fetchStudentList}" value="{!this}" />  
       <aura:iteration items="{!v.studentList}" var="student">  
         <div data-id ="{!student.Id}" class="slds-box slds-theme_shade" onclick="{!c.handleSelect}">  
           {!student.Name}  
         </div>  
       </aura:iteration>  
     </aura:component>  
    

    StudentListController.js
     ({  
       fetchStudentList : function(component, event, helper) {  
         var action = component.get("c.getStudentList");  
         action.setCallback(this, function(response) {  
           var state = response.getState();  
           if(state === 'SUCCESS') {  
             var studentList = response.getReturnValue();  
             component.set("v.studentList",studentList);  
           }  
           else {  
             alert('Error in getting data');  
           }  
         });  
         $A.enqueueAction(action);  
       },  
       handleSelect: function(component, event, helper) {  
         var selectedId = event.target.dataset.id;  
         alert(selectedId)  
       }  
     })  
    


    Output:

  • How To Use LWC Lookup Component in Lightning Aura Component

    salesforcepoint Friday, 10 July 2020

    Implement LWC Lookup In Aura:


    Use LWC Lookup in Aura Component: In this post we are going to see how to refer Lookup component (created in LWC) in aura component and we will come to know how to handle event dispatched by LWC component in Aura component. On Lwc lookup component we are dispatching recordselection event along with  selectedRecordId, selectedRecordValue. In parent Aura component we are handling event onrecordselection into onAccountSelection function and setting selectedRecordId, selectedRecordName values with selectedRecordId, selectedRecordValue from event.

    Create new lightning aura component: HandleLwcLookupInAura

    HandleLwcLookupInAura.cmp
     <aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >  
       <aura:attribute name="selectedRecordId" type="String" />  
       <aura:attribute name="selectedRecordName" type="String" />  
       <div class="slds-box">  
         <c:lwcLookup objectApiName='contact' iconName='standard:contact' onrecordselection="{!c.onAccountSelection}"/>  
       </div>  
       <div class="slds-box">  
         Selected Record Name : {!v.selectedRecordName} <br/>  
         Selected Record Id : {!v.selectedRecordId}   
       </div>  
     </aura:component>  
    

    HandleLwcLookupInAuraController.js
     ({  
          onAccountSelection : function(component, event, helper) {  
               component.set("v.selectedRecordName", event.getParam('selectedValue'));  
               component.set("v.selectedRecordId", event.getParam('selectedRecordId'));  
          }  
     })  


    Output:

  • How to Show & Hide Lightning Spinner in Salesforce

    salesforcepoint Wednesday, 18 April 2018
    Spinner is component loading indicator that should be shown when retrieving data or performing slow computations or server operations. Spinner needs to be stop displaying after operations.


     we can get spinners in two ways.

    1. with standard events like aura:waiting & aura:doneWaiting : We can use this when spinner needs to be shown when all server operations means calling apex classes and receiving response.

     2. With custom events: We use this type when we need to show spinner when event occurs only like 'I need to show Spinner when user clicks on Save button'. For this we need to to define on Boolean attribute to rendering spinner.

    Show & Hide Lightning Spinner Example:

    Spinner.cmp
    
    <aura:component >
        <aura:attribute name="showSpinner" type="Boolean"/>
        <lightning:button variant="brand" label="cancel" onclick="{!c.cancel }" />
        <lightning:button variant="brand" label="Show Spinner" onclick="{!c.Show}" />
        <aura:if isTrue="{!v.showSpinner}">
            <div class="demo-only" >
                <div role="status" class="slds-spinner slds-spinner_large slds-spinner_brand">
                    <span class="slds-assistive-text">Loading</span>
                    <div class="slds-spinner__dot-a"></div>
                    <div class="slds-spinner__dot-b"></div>
                </div>
            </div>
        </aura:if>
    </aura:component>
    

    SpinnerController.js
    ({
    Show : function(component, event, helper) {
      component.set("v.showSpinner",true);
      },
    cancel : function(component, event, helper) {
       component.set("v.showSpinner", false);
       }
    }) 
    OutPut:

  • How to pass parameters from Lightning component to Controller.js(client side controller) with example

    salesforcepoint Monday, 19 February 2018

    Lightning Tutorials Basics: Passing parameters from Lightning component to Controller.js(client side controller) and controller to Lightning component:


    In this tutorial we are going to learn how to pass parameters from Lightning component to controller vice versa.

    By using component.get(v.attrinuteName) or  component.find("aura:id").get("v.value") we can pass value from component to controller.
    By using component.set("v.attrinuteName",value);  we can pass value from controller to lightning component.

    In below code  empName attribute used to store the data which is entered by user in ui:inputText.
    when user click on button "callme" function gets called and the value entered in inputText box will be passed to the attribute "empName" and the result will be printed.
    <aura:component >
        <aura:attribute name="empName" type="String"/>
        <aura:attribute name="emp" type="String"/>
        <ui:inputText label="Enter Name"  aura:id="name" />
        <ui:button label="submit" press="{!c.callme}" /> <br />
        Employee Name Entered:  <ui:outputText value="{!v.empName}" />
    </aura:component>



    FirstComponent.js
    
    ({
        callme : function(component, event, helper) {
        var Name = component.find("name").get("v.value");
        component.set("v.empName",Name )
        }
    })
    Check Output
    FitstComponentApp.app

    <aura:application >
        <c:FirstComponent />
    </aura:application>

    when user entered something in input box and click on submit button "callme" function gets called and the value entered in inputText box will be passed to the attribute "empName" and the result will be printed as output below...

  • Lightning Component Basics: Add Two Numbers

    salesforcepoint Saturday, 16 December 2017
    In this post we are going to learn what is Attributes in Lightning Component and how to use it in components.

    Attributes: Lightning Component Attributes are like  member variables in apex class.

    syntax: <aura:attribute name=" " type=" " default=" " />
     here name and type are required.

    ex: <aura:attribute name="Salesforce" type="String"  />


    Add2nums.cmp

    <aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="Number1" type="Integer" default="20" />
            <aura:attribute name="Number2" type="Integer" default="30" />
            <aura:attribute name="Sum" type="Integer" />
              {!v.Number1}+{!v.Number2}={!v.Sum}
        <br/> <br />
        <ui:button label="Click Here" press="{!c.add}" />
    </aura:component>

    Add2numscontroller.js

    ({
    add : function(component) {
            var add2=component.get("v.Number1")+component.get("v.Number2");
            component.set("v.Sum",add2);
    }

    })

    Add2nums.app

    <aura:application >
        <c:Add2nums/>
    </aura:application>

    output:
    when we click button Java script function get called and will set the value to {!v.Sum}