Browsing "Older Posts"

  • 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:

  • Navigate/Redirect To Record Page Based On Record Id In LWC (Lightning Web Component)

    salesforcepoint

    Redirect or Navigate to salesforce object record detail page in Lwc:

    How to Navigate to record page in Lwc in lightning web component


    In many scenarios we need to redirect to record detail page upon successful record save or update into database. Below code is helpful for navigate to sobject record page in Lightning web components. For navigating to record page in lightning experience we need to use lightning navigation service.

    Implementation steps to navigate/Redirect to record page in LWC components: 

    For Using navigation service in Lwc we need to import NavigationMixin  from lightning/navigation base.
    
    import { NavigationMixin } from 'lightning/navigation';
    
    

    Then we need to Apply the NavigationMixin function to your component’s base class.
    
    export default class MyCustomElement extends NavigationMixin(LightningElement) {
    }
    
    
    Add new function to redirect to record page in JavaScript and specify object api name, record id in objectApiName and recordId attributes. Call this function wherever you want (Like after success return from apex).
    
    navigateToRecordPage() {
            this[NavigationMixin.Navigate]({
                type: 'standard__recordPage',
                attributes: {
                    recordId: 'recordId',
                    objectApiName: 'ObjectApiName',
                    actionName: 'view'
                }
            });
    }
    
    

    Example: in below example we create new button, once we click on button tit should redirect to specified account record page.

    redirectToRecordPage.html
     <template>  
       <div class="slds-box slds-theme_shade">  
         <lightning-button label="Navigate To Account" onclick="{navigateToAccountPage}"> </lightning-button>  
       </div>  
     </template>  
    



    redirectToRecordPage.js
     
    import { LightningElement } from 'lwc';
    import { NavigationMixin } from 'lightning/navigation';
    
    export default class RedirectToRecordPage extends NavigationMixin(LightningElement) {
    
        navigateToAccountPage() {
            this[NavigationMixin.Navigate]({
                type: 'standard__recordPage',
                attributes: {
                    recordId: '0010K000027o6pWQAQ',
                    objectApiName: 'Account',
                    actionName: 'view'
                }
            });
     }
    }
    
    

    Output:
  • How To Display LWC Component In Quick Action

    salesforcepoint Saturday, 25 July 2020

    Lighting Web Component (LWC)  In Quick action 

    We can't show lwc component directly in lightning quick action, if we need to show Lightning web component in quick action then we need to create simple lightning aura component and in that we need to refer Lwc component (check example code below). Then we can show lwc component content in quick action button.

    Showing LWC Component content in Lightning Quick Action 

    Step 1: Create new lightning web component : lwcAction
    lwcAction.html
     <template>  
       <div class="slds-box slds-theme_shade">  
         <P> I am from LWC Component</P>  
       </div>  
     </template>  
    
    Step2: Create new lightning aura component LwcInAuraQuickAction


    LwcInAuraQuickAction.cmp
     <aura:component implements="flexipage:availableForAllPageTypes,  
                   flexipage:availableForRecordHome,  
                   force:hasRecordId,force:lightningQuickAction" access="global" >  
       <c:lwcAction />  
     </aura:component>  
    

    Add it to quick action button

    Go to Object Manger--> Buttons, Links, and Actions --> New Action 
    --> Select Lightning Component as Action Type
    --> Select LwcInAuraQuickAction as Lightning Component
    --> Give "LWC ACtion" as Label and save.
    Lightning web component Quick Action Example code
    --> Add this "LWC Action" button to page layout.

    Output:

  • LWC Modal: How To Create/Show Modal Popup in LWC

    salesforcepoint

    How Display Content In Modal Popup window using Lightning Web Components (LWC):

    If we need to show something in modal dialog we need to use predefined slds class "slds-modal" . LWC modal has three section i.e header, body(modal content), footer. If we use "slds-modal__header" class we can show sticky header in modal window and by using "slds-modal__footer" class we can show sticky footer where usually show save, cancel buttons. By using "slds-modal__content" class we can show modal body content.

    In below example code we are showing lightning button, on click of that button, modal popup window will be opened.

    Code for Lightning Web Component (LWC) Modal Popup 

    Create new lightning web component: lwcModalPopup



    lwcModalPopup.html
     <template>  
       <div class="slds-box slds-theme_shade">  
         <lightning-button label="Show Modal" onclick={showModal}> </lightning-button>  
       </div>  
       <template if:true={openModal}>  
         <div class="slds-modal slds-fade-in-open slds-backdrop">  
           <div class="slds-modal__container">  
             <!------HEADER Section-->  
             <div class="slds-modal__header">  
               <lightning-button-icon icon-name="utility:close" alternative-text="Close this window" size="large"  
                 variant="bare-inverse" onclick={closeModal} class="slds-modal__close">  
               </lightning-button-icon>  
               <h2>Welcome To SalesforcePoint.com</h2>  
             </div>  
             <!------Body Section-->  
             <div class="slds-modal__content slds-p-around_medium">  
               <center>  
                 <P>Hello guys, welcome to salesforcepoint.com. <br>  
                   This is the basic lightning web component Modal popup.  
                 </P>  
               </center>  
             </div>  
             <!------Footer Section-->  
             <div class="slds-modal__footer">  
               <lightning-button icon-name="utility:close" label="close" variant="brand" onclick={closeModal}>  
               </lightning-button>  
             </div>  
           </div>  
         </div>  
       </template>  
     </template>  
    
    lwcModalPopup.js
    
    import { LightningElement,track } from 'lwc';
    export default class LwcModalPopup extends LightningElement {
        @track openModal = false;
        showModal() {
            this.openModal = true;
        }
        closeModal() {
            this.openModal = false;
        }
    }
    
    Deploy the modal component and add it lightning page.

    Output:


    LWC Modal popup Lightning web component code
    Output of LWC Modal component

  • Create Calculator Using Lightning Web Component(LWC)

    salesforcepoint

    Simple LWC Calculator

    In this we are going to see how to create or build simple lightning web component calculator  with functions like 
    • How to add two numbers in Lwc.
    • How to subtract two numbers in Lwc. 
    • Division of two numbers in Lwc.
    • Multiplication of two numbers in Lwc.

    Steps to create Lightning Web Component Calculator

    Step1 : Create New Lightning Web component with name: calculatorInLwc.
    calculatorInLwc.html
     <template>  
        <div class="slds-box slds-theme_shade">  
         <lightning-input type="number" name="input2" label="Number 1" onchange={handleNumberOeChange} value={firstNumber}></lightning-input>  
         <lightning-input type="number" name="input2" label="Number 2" onchange={handleNumberTwoChange} value={secondNumber}></lightning-input>  
       </div>  
       <div class="slds-box slds-theme_shade">  
         <b>Output value is : </b>  
          <P>{resultValue}</p>  
       </div>  
        <div class="slds-box slds-theme_shade">  
         <lightning-button label="Addition" onclick={addition}> </lightning-button>  
         <lightning-button label="Multification" onclick={multification}> </lightning-button>  
         <lightning-button label="Subtraction" onclick={subtraction}> </lightning-button>  
         <lightning-button label="Divison" onclick={division}> </lightning-button>  
        </div>  
     </template>  
    

    calculatorInLwc.js
    
    import { LightningElement, track } from 'lwc';
    export default class CalculatorInLwc extends LightningElement {
        @track firstNumber;
        @track secondNumber;
        resultValue;
        handleNumberOeChange(event) {
            this.firstNumber = parseInt(event.target.value);
        }
        handleNumberTwoChange(event) {
            this.secondNumber = parseInt(event.target.value);
        }
        addition() {
            this.resultValue = parseInt(this.firstNumber) + parseInt(this.secondNumber);
        }
        multification() {
            this.resultValue = this.firstNumber * this.secondNumber;
        }
        subtraction() {
            this.resultValue = this.firstNumber - this.secondNumber;
        }
        division() {
            this.resultValue = this.firstNumber / this.secondNumber;
        }
    }
    

    Step2: Add this lwc component to lightning page.
    Add calculator Lightning web competent to lightning page in app builder.

    Output:


  • Populate Preselected Checkbox for Records/Rows On LWC Lightning Data Table Using Wrapper Class

    salesforcepoint Sunday, 19 July 2020
    Populate  Preselected Checkbox for Records/Rows On LWC Lightning Data Table

    Lightning Data Table with Pre populated selected records in Lightning Web Components   

    In some scenarios we need auto populate selected checkbox for records in lightning-datatable on page load. In this post we also covered how to use wrapper class in Lightning web components (LWC).Let's see how to populate preselected rows in LWC data table.

    Also Check: How To Add Hyper Link For Name Column In lightning-datatable in LWC

    We have a key-field attribute in lightning-datatable  tag which is unique for every row in the table and based on this field only we can populate pre selected checkbox in data table. By using "selected-rows" attribute we can set the on load selected records in lightning-datatable, this is a array of unique key-field values. As per the requirements we set this attribute value in code.

    Example for preselected rows/records in LWC data table:

    Display all opportunity records and all these records should be pre selected.

    Step1: Create Apex class: OpportunityController.

    
    public with sharing class OpportunityController {  
       @AuraEnabled(cacheable=true)  
       public static oppWrapper getOpportunityRecords(){  
         oppWrapper ow = new oppWrapper();  
         ow.oppList = [SELECT Id, Name, StageName,Amount From Opportunity LIMIT 100];  
         Set<Id> selectedOppIdSet = new Set<Id>();  
         for(Opportunity opp: ow.oppList){  
           selectedOppIdSet.add(opp.Id);  
         }  
         ow.selectedIdSet = selectedOppIdSet;  
         return ow;  
       }  
          public class oppWrapper{  
         @AuraEnabled public List<opportunity> oppList {get; set;}  
         @AuraEnabled public set<Id> selectedIdSet {get; set;}  
       }  
     }  
    

    Step2: Create New lightning web component: preSelectedLightningDataTable.



    preSelectedLightningDataTable.js
    
    import { LightningElement,track,wire } from 'lwc';
    import getOpportunityList from '@salesforce/apex/OpportunityController.getOpportunityRecords';
    const COLS=[
        {label:'Name',fieldName:'Name', type:'text'},
        {label:'Stage',fieldName:'StageName', type:'text'},
        {label:'Amount',fieldName:'Amount', type:'currency'}
    ];
    export default class PreSelectedLightningDataTable extends LightningElement {
        oppList;
        cols = COLS;
        @track preSelectedRows;
    
        @wire(getOpportunityList)
        getOpportunityList(result){
            if(result.data) {
                this.oppList=result.data.oppList;
                this.preSelectedRows = result.data.selectedIdSet;
                this.errorList=undefined;
            }else if(result.error){
                this.oppList=undefined;
                this.errorList=result.error;
            }
        }
    }
     
    preSelectedLightningDataTable.html


    
    <template>  
       <lightning-card title="Opportunity Records">  
         <div class="slds-box">  
           <lightning-datatable selected-rows={preSelectedRows}  
           data={oppList} columns={cols} key-field="Id">  
           </lightning-datatable>  
         </div>  
       </lightning-card>  
     </template>  
    

    Output: Data Table with Pre populated selected checkbox records in Lightning Web Components.
    How To Populate  Preselected Checkbox for Records/Rows On LWC Lightning Data Table2
  • How To Iterate Array/List In Lightning Web Components (LWC)

    salesforcepoint Friday, 10 July 2020

    How To Iterate List Of Items In LWC


    Iterate array of elments in LWC html template



    LWC iteration: In this post we will see how to use iteration in Lightning Web Components template. Like aura:iteration in Aura, we have "for:each" in lwc. By using "for:each" we can iterate set of elements/items in lwc html template. We can access element by using for:item and we can get index value with for:index .

    Syntax: 
     <template for:each={itemList} for:item="item" for:index="index">  
      {item}  
     </template>  

    Iteration in lwc html Example: Iterate List of Accounts.


    Create apex class: IterationInLwcController
     public with sharing class IterationInLwcController {  
       @AuraEnabled(cacheable = true)  
       public static List<Account> fetchAccounts(){  
         return [SELECT Id,Name,Phone,Type,Industry,Rating,Website FROM Account LIMIT 100];  
       }  
     }  
    

    Create New Lightning Web Component: iterationInLwc


    iterationInLwc.html
    If you getting list from wired property then, we need o use list.data to "for:each". Because wired property contains data and error. 
     <template>  
       <lightning-card title="Iteration In LWC">  
         <div class="slds-p-around_small">  
           <template for:each={accounts.data} for:item="account" for:index="index">  
             <div class="slds-p-left_small" key={account.Id}>  
               {account.Name}  
             </div>  
           </template>  
         </div>  
       </lightning-card>  
     </template>  
    

    iterationInLwc.js


     import { LightningElement, wire } from 'lwc';  
     import fetchAccounts from '@salesforce/apex/IterationInLwcController.fetchAccounts';  
     export default class IterationInLwc extends LightningElement {  
       @wire(fetchAccounts) accounts;  
     }  
    

    Output: 

  • How To Use LWC Lookup Component in Lightning Aura Component

    salesforcepoint

    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:

  • Reusable Custom LWC Lookup Component

    salesforcepoint Thursday, 9 July 2020

    How to use Lookup in Lightning web components: 

    Lookup Component In Lightning Web Components

    LWC Lookup Component :

    In this post we are going to see how to create/use lookup field in lwc input forms. Unlike other fields we don't have predefined tag for lookup field in LWC, if you want to achieve lookup functionality in lightning web components we need to write our own code. 

    Note: By using lightning-record-edit-form we can achieve lookup functionality, but that may not be helpful if we need to pre-populate value in the lookup field and need to show records based on filter conditions. But custom code supports all the functionalities based on our customization. 

    Custom LWC Lookup component code


    1. Create Apex class: LwcLookupController
     public class LwcLookupController {  
       @AuraEnabled(cacheable=true)  
       public static List<sobject> findRecords(String searchKey, String objectName) {  
         string searchText = '\'' + String.escapeSingleQuotes(searchKey) + '%\'';  
         string query = 'SELECT Id, Name FROM ' +objectName+ ' WHERE Name LIKE '+searchText+' LIMIT 6';  
         return Database.query('SELECT Id, Name FROM ' +objectName+ ' WHERE Name LIKE '+searchText+' LIMIT 6');  
       }  
     }  
    

    2. Create new Lightning web component: lwcLookup

    lwcLookup.js
     import { LightningElement, track, wire, api } from "lwc";  
     import findRecords from "@salesforce/apex/LwcLookupController.findRecords";  
     export default class LwcLookup extends LightningElement {  
      @track recordsList;  
      @track searchKey = "";  
      @api selectedValue;  
      @api selectedRecordId;  
      @api objectApiName;  
      @api iconName;  
      @api lookupLabel;  
      @track message;  
        
      onLeave(event) {  
       setTimeout(() => {  
        this.searchKey = "";  
        this.recordsList = null;  
       }, 300);  
      }  
        
      onRecordSelection(event) {  
       this.selectedRecordId = event.target.dataset.key;  
       this.selectedValue = event.target.dataset.name;  
       this.searchKey = "";  
       this.onSeletedRecordUpdate();  
      }  
       
      handleKeyChange(event) {  
       const searchKey = event.target.value;  
       this.searchKey = searchKey;  
       this.getLookupResult();  
      }  
       
      removeRecordOnLookup(event) {  
       this.searchKey = "";  
       this.selectedValue = null;  
       this.selectedRecordId = null;  
       this.recordsList = null;  
       this.onSeletedRecordUpdate();  
     }  
       
    
    
    
      getLookupResult() {  
       findRecords({ searchKey: this.searchKey, objectName : this.objectApiName })  
        .then((result) => {  
         if (result.length===0) {  
           this.recordsList = [];  
           this.message = "No Records Found";  
          } else {  
           this.recordsList = result;  
           this.message = "";  
          }  
          this.error = undefined;  
        })  
        .catch((error) => {  
         this.error = error;  
         this.recordsList = undefined;  
        });  
      }  
       
      onSeletedRecordUpdate(){  
       const passEventr = new CustomEvent('recordselection', {  
         detail: { selectedRecordId: this.selectedRecordId, selectedValue: this.selectedValue }  
        });  
        this.dispatchEvent(passEventr);  
      }  
     }  
    

    lwcLookup.html
     <template>  
       <div class="slds-form-element">  
         <label class="slds-form-element__label" for="combobox-id-2">{lookupLabel}</label>  
         <div class="slds-form-element__control">  
           <div class="slds-combobox_container">  
             <div class="slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click slds-is-open" aria-expanded="true" aria-haspopup="listbox" role="combobox">  
               <template if:true={selectedValue}>  
               <div data-key="pilldiv" class="slds-combobox__form-element slds-input-has-icon slds-input-has-icon_left-right" role="none">  
                 <span class="slds-icon_container slds-icon-standard-account slds-combobox__input-entity-icon" title="object">  
                  <div class="slds-icon slds-icon_small" aria-hidden="true">  
                   <lightning-icon icon-name={iconName} size="small"></lightning-icon>  
                  </div>  
                  <span class="slds-assistive-text">Record</span>  
                 </span>  
                 <input type="text" class="slds-input slds-combobox__input slds-combobox__input-value" id="combobox-id-5" aria-controls="listbox-id-5" role="textbox" placeholder="Select an Option" readonly value={selectedValue} />  
                 <button class="slds-button slds-button_icon slds-input__icon slds-input__icon_right" onclick={removeRecordOnLookup}  
                 title="Remove selected option">  
                  <span class="slds-button__icon" aria-hidden="true" >  
                   <lightning-icon icon-name="utility:close"   
                    size="xx-Small" class="slds-icon slds-icon slds-icon_x-small slds-icon-text-default" aria-hidden="true"></lightning-icon>  
                  </span>  
                  <span class="slds-assistive-text">Remove selected record</span>  
                 </button>  
                </div>  
               </template>  
       
               <template if:false={selectedValue}>  
               <div data-key="searchdiv" class="slds-combobox__form-element slds-input-has-icon slds-input-has-icon_right" role="none">  
                 <input type="text" onfocusout={onLeave} value={searchKey} onkeyup={handleKeyChange} onchange={handleKeyChange} class="slds-input slds-combobox__input slds-has-focus" id="combobox-id-2" aria-autocomplete="list" aria-controls="listbox-id-2" role="textbox" placeholder="Search..." />  
                 <span class="slds-icon_container slds-icon-utility-search slds-input__icon slds-input__icon_right">  
                   <lightning-icon icon-name="utility:search" size="xx-Small" class="slds-icon slds-icon slds-icon_x-small slds-icon-text-default" aria-hidden="true"></lightning-icon>  
                 </span>  
               </div>  
       
               <template if:true={recordsList}>  
               <div id="listbox-id-2-venu" data-key="dropdownresult" class="slds-show slds-dropdown slds-dropdown_length-with-icon-7 slds-dropdown_fluid" role="listbox">  
                 <ul class="slds-listbox slds-listbox_vertical" role="presentation" >  
                   <template if:true={message}>  
                   <center> {message}</center>  
                   </template>  
                   <template for:each={recordsList} for:item="record">  
                     <li id={record.Id} key={record.Id} onclick={onRecordSelection} role="presentation" class="slds-listbox__item">  
                     <div data-key={record.Id} data-name={record.Name} class="slds-media slds-listbox__option slds-listbox__option_entity slds-listbox__option_has-meta" role="option">  
                       <span class="slds-media__figure slds-listbox__option-icon">  
                         <span class="slds-icon_container">  
                           <lightning-icon icon-name={iconName} size="small"></lightning-icon>  
                         </span>  
                       </span>  
                       <span class="slds-media__body">  
                         <span data-key={record.Id} data-name={record.Name} class="slds-listbox__option-text slds-listbox__option-text_entity">{record.Name} </span>  
                       </span>  
                     </div>  
                   </li>  
                   </template>  
                 </ul>  
               </div>  
               </template>  
               </template>  
             </div>  
           </div>  
         </div>  
       </div>  
     </template>  
    

    Now we are done with lookup component creation. Let's see how to use it in another Lightning web component.

    Important public properties we need to pass to lookup component.




    1. objectApiName (object-api-name) : Which object records we are going to fetch on lookup. This is required property.
    2. iconName (icon-name) : This is used to show object specific icon in lookup list and selected record.
    3. selectedRecordId (selected-record-id ): If we need to pre populate selected record on load, then we need to assign record id which we should show on lookup.
    4. selectedValue (selected-value ): Pre Selected record name.

    Important event we need to handle on parent Lwc component:

    onrecordselection: This event gets fired every time when new record selected or selected record removed on lookup. By using this event we can get the selected record id
    (event.detail.selectedRecordId) and name (event.detail.selectedValue) values. check below example code.

    3. Create Demo Lightning web component: lwcLookupDemo
    This component is used for checking output of lookup component. In below example we are fetching lookup records from Account object and we are handling onrecordselection event on "onAccountSelection" functtion.

    lwcLookupDemo.js
     import { LightningElement, track } from 'lwc';  
     export default class LwcLookupDemo extends LightningElement {  
       @track accountName;  
       @track accountRecordId;  
    
       onAccountSelection(event){  
       this.accountName = event.detail.selectedValue;  
       this.accountRecordId = event.detail.selectedRecordId;  
       }  
     }  
    

    lwcLookupDemo.html
     <template>  
       <div class="slds-box">  
         <c-lwc-lookup lookup-label="Account" object-api-name="account" icon-name="standard:account"  
           onrecordselection={onAccountSelection}></c-lwc-lookup>  
       </div>  
       <div class="slds-box">  
         Selected Account Name : {accountName}  
         Selected Account Id  : {accountRecordId}  
       </div>  
     </template>  
    

    4. Add component to App builder page: Add this demo lwc component to app builder page to see output of Lookup.

    LWC Lookup component output

    Check how to use this LWC lookup component in Lightning Aura Component
  • Salesforce Apex Map & Map methods with Examples

    salesforcepoint Wednesday, 8 July 2020
    Salesforce Apex Map, Map methods with Examples
    Map is one of the collection type in salesforce apex. In this post we are going to see what are the map methods with some basic examples. First of all Map is a key and value pair i.e each and every value is associates with key. Here key is unique, that means if we put one key,value pair into Map, we should not add same key one more time. If key is already exist in map and once again you are trying to add key with different value then old value override with new value.

    Salesforce Apex Map Syntax:

    Map<dataType, dataType> variabeName ;

    If we don't initialize map and 'trying to put new set of key, value' Or trying to use any map methods on that variable, you will end up with null pointer exception. So we need to initialize map whenever we create map variable.

    Map<dataType, dataType> variabeName = new Map<dataType, dataType>();

    eg: Map<String, String> countryWithCapitalMap =  new Map<String, String>();

    Important Apex Map Methods:

    put( ): By using this method we can new set of key, value pair into map.
    example: countryWithCapitalMap.put('India', 'Delhi'); //here India is key & Delhi is corresponding value for key 'India'.

    containsKey(key): By using this method we can check whether key exist or not in Map. It will return true if key is exist in apex map.
    example: countryWithCapitalMap.containsKey('India') //true

    get(Key): It returns value of corresponding key.
    example:  countryWithCapitalMap.get('India') //reurns 'Delhi'

    isEmpty(): It returns true if Map does not contain any key, value pair.
    example:  countryWithCapitalMap.isEmpty() //false

    size():  It returns number of key, value pairs available in Map.
    example: countryWithCapitalMap.size() // 1

    keySet(): It returns SET of key's available in the map.
    example: countryWithCapitalMap.keySet() //{India}

    values(): It returns LIST of values available in map.
    example: countryWithCapitalMap.values() //{Delhi}

    Task: Create a map to store country as Key and corresponding countries as values.

    Country (Key)
    'United States'
    'India'
    States (Value)
    'California',
    'Colorado',
     'Texas' 
    'Andhra Prdesh',
    'Telangana',
    'Karnataka'

    One country can have multiple states so that we should create Map value as List<string>

    Map<String, List<String>> countryWithStatesMap = new Map<String, List<String>>();

    countryWithStatesMap.put('United States', new List<String>{'California','Colorado','Texas'});
    countryWithStatesMap.put('India', new List<String>{'Andhra Prdesh','Telangana','Karnataka'});

    system.debug('Get countries from countryWithStatesMap ===>'+countryWithStatesMap.keyset());
    // o/p: {India, United States}
    system.debug('Get States of India ===>'+countryWithStatesMap.get('India'));
    // o/p: (Andhra Prdesh, Telangana, Karnataka)
    system.debug('Is Srilanka there in Map ===>'+countryWithStatesMap.containsKey('Srilanka')); 
    // o/p: false