Latest Posts

LWC

Lightning Aura Components

Apex

Recent Posts

  • Salesforce Lightning Web Components - LWC Interview Questions

    salesforcepoint Monday, 3 August 2020

    Latest LWC Interview Questions 

    Latest LWC Interview Questions

    1. What is LWC?
    2. Difference between Lightning web components and Lightning aura components?
    3. How to fire child lightning web component function from parent LWC component?
    4. How to pass data from child LWC component to parent lightning aura component?
    5. How to get dynamic record id in LWC? Answer: By using @api recordId; property we can dynamically fetch current record id in lightning web component.
    6. What is difference between const, let and var types?
    7. What's the difference between wire function imperative functon?
    8. Is it possible to use lwc component in quick action?
    9. Why wire function gets invoked multiple times?
    10. What is the importance of Constructor in LWC?
    11. What are the differences between @api, @wire @track lwc decorators?
    12. What is the purpose of refreshApex() in LWC? Ex: https://www.salesforcepoint.com/2020/06/lwc-data-table-with-checkbox-example.html
    13.  What is the meta data name of Lightning web component?  Ans: LightningComponentBundle
    14. When will we get "Cannot Assign To Read Only Property Error" In LWC? How can we resolve that issue?
    15. Can we refer lightning aura component inside Lightning web component?
    Hello folks post your answers for above mentioned Lightning web component interview questions? 

    Other LWC tutorials click herehttps://www.salesforcepoint.com/search/label/LWC

  • How To Fix Cannot Assign To Read Only Property Error In LWC-Lighting Web Components

    salesforcepoint Sunday, 2 August 2020

    Fix Cannot Assign To Read Only Property Error In LWC In Lightning web components 

    How To Fix Cannot Assign To Read Only Property Error In Lightning Web Components

    If we are trying to update public (@api) property or wired property in JavaScript function we usually get this issue. For resolving this issue, we need to clone that property to new variable and update it. After updating assign temporary variable to actual property.

     Example Problem Code:
     allCheckBoxChange(event) {
            for (let j = 0; j < this.allOppList.length; j++) {
                this.allOppList.isChecked = event.detail.checked;
            }
        }

    In above code "allOppList" is the data of wired property. When allCheckBoxChange() fynction gets invoked we will get below error Uncaught TypeError: Cannot assign to read only property '0' of object '[object Array]'

    Solution Code:
     allCheckBoxChange(event) {
            let tempAllRecords = Object.assign([], this.allOppList);
            for (let j = 0; j < this.allOppList.length; j++) {
                    let tempRec = Object.assign({}, tempAllRecords[j]);
                    tempRec.isChecked = event.detail.checked;
                    tempAllRecords[j] = tempRec;
            }
            this.allOppList = tempAllRecords;
    }

    In above code we are cloning wired property "allOppList" to new temporary variable tempAllRecords and after update, assigning temporary list to allOppList. In for loop we are updating every record of allOppList, so we are cloning every record and updating the cloned record and assigning back to actual record. So that we can avoid read only property issue.

     Note: Object.assign() function is the one of cloning method in JavaScript.
  • How To Display [Object Object] In console.log or Alert in JavaScript (LWC & Lightning Aura Components)

    salesforcepoint Saturday, 1 August 2020

    Display [Object Object] As String In JavaScript: 

    Display Object as String in JavaScript

    In JavaScript if we trying to print other than primitive type variables in console.log or alert, then it will returns [Object Object]. If its return output as [Object Object], we can't know output as expected or not.

    By using JSON.stringify() function we can print output in string format. JSON.stringify() is a predefined JavaScript function, it takes object as a input parameter and returns json string if object in JavaScript specific object structure.

    Example:  Display Object as String in js

    var cObj = { name: "Salesforec", age: 10, city: "CA" };
    console.log("cObj===>"+cObj ); //output : cObj===>"+[Object Object]
    console.log("cObj in String Format===>"+JSON.stringify(cObj) );
    // output: cObj in String Format===> { name: "Salesforec", age: 10, city: "CA" };
  • LWC Picklist : Get Values Without Default RecordTypeId and Based on RecordTypeId

    salesforcepoint Tuesday, 28 July 2020

    Fetching and Displaying Picklist Values In Lightning Web Components (LWC) : 

    By using "lightning-combobox" tag we can display picklist values in Lwc markp. In Lightning Aura Components if we want to display picklist values, we need to hit  apex server and needs write logic to fetch picklist values by using dynamic schema. Even though we are write apex logic, we could not get picklist values based on recordtype name or recordTypeId, every time it shows all the values irrespective of record type. But in lightning web components we have a great privilege that don't need to hit apex for fetching picklist values. In Lwc we can get values based on recordtype name as well.

    By importing getPicklistValues or getPicklistValuesByRecordType from "lightning/uiObjectInfoApi" we can get picklist values in LWC JavaScript. recordTypeId is required parameter for both of these functions.

    Get picklist values based on recordtypeId In Salesforce LWC component


    lwcPicklistWithRecordtype.js
    import { LightningElement,wire } from 'lwc';
    import { getPicklistValues } from 'lightning/uiObjectInfoApi';
    import STAGE from '@salesforce/schema/Opportunity.StageName';
    
    export default class LwcPicklistWithRecordtype extends LightningElement {
        @wire(getPicklistValues,
            {
                recordTypeId: '01228000000XckuAAC', //pass id dynamically
                fieldApiName: STAGE
            }
        )
        stageValues;
    }

    lwcPicklistWithRecordtype.html
    <template>
        <div class="slds-box">
            <template if:true={stageValues.data}>
                <lightning-combobox name="progress" label="Opportunity Stage" value={value} 
                    options={stageValues.data.values} onchange={handleChange}>
                </lightning-combobox>
            </template>
        </div>
    </template>

    Output LWC picklist values based on recordtype values

    Get picklist values if we don't have recordtypes in Object In Lightning Web Components (LWC)

    If  object does not have record type's then use the defaultRecordTypeId property, this can be fetch from  getRecordUi or getObjectInfo. See below example.

    lwcPicklistWithoutRecordtype.js
    import { LightningElement,wire } from 'lwc';
    import { getPicklistValues } from 'lightning/uiObjectInfoApi';
    import LeadSource from '@salesforce/schema/Contact.LeadSource';
    import { getObjectInfo } from 'lightning/uiObjectInfoApi';
    import CONTACT_OBJECT from '@salesforce/schema/Contact';
    
    export default class LwcPicklistWithoutRecordtypeextends LightningElement {
        @wire(getObjectInfo, { objectApiName: CONTACT_OBJECT })
        contactInfo;
    
        @wire(getPicklistValues,
            {
                recordTypeId: '$contactInfo.data.defaultRecordTypeId',
                fieldApiName: LeadSource
            }
        )
        leadSourceValues;
    }
    lwcPicklistWithoutRecordtype.html
    <template>
        <div class="slds-box">
            <template if:true={leadSourceValues.data}>
                <lightning-combobox name="progress" label="Lead Source" value={value}
                    options={leadSourceValues.data.values} onchange={handleChange}>
                </lightning-combobox>
            </template>
        </div>
    </template>


    Outut: LWC picklist values based on recordtype
  • 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:


  • How To Populate Preselected Checkbox for Records/Rows On LWC Lightning Data Table

    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. 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



    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>  

    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
  • LWC Custom File Upload Component Along With New Record Creation

    salesforcepoint Sunday, 28 June 2020
    How To Create New Record along with File Upload in Lightning Web Component(LWC)  : 
    In this post we are going to see how to upload files/attachments into Salesforce object by using Lightning Web Component. If we use "lightning-file-upload" tag we cant insert file along with record (yet to be inserted into database). Because lightning-file-upload requires record id for enabling upload option, but at that time record id not available as record not inserted yet. So we are using lightning-input type="file" tag for uploading file. But if we use this we need to write our own logic to insert file using apex unlike "lightning-file-upload". By using this we can upload JPEG, PNG images, Pdf etc. Check below example code.

    Example: Create New Contact Record form along with File upload option:

    Step 1: Create a apex controller for handling contact record and file insertion.

    ContactController


     public with sharing class ContactController {  
       @AuraEnabled  
       public static string saveContact(Contact contactRec, string file, string fileName) {  
         string contactId;  
         try{  
           Insert contactRec;  
           contactId = contactRec.Id;  
           base62File = EncodingUtil.urlDecode(base62File, 'UTF-8');     
           ContentVersion contentVersionRec = new ContentVersion();  
           contentVersionRec.Title = fileName;  
           contentVersionRec.PathOnClient = '/' + fileName;  
           contentVersionRec.FirstPublishLocationId = contactRec.Id;  
           contentVersionRec.VersionData = EncodingUtil.base64Decode(base62File);  
           contentVersionRec.IsMajorVersion = true;  
           Insert contentVersionRec;  
         } catch(Exception ex){  
           system.debug('Exception===>'+ex.getMessage());  
         }  
         return contactId;  
       }    
     }  
    

    Step 2: Create Lightning Web Component 

    newRecordWithFileUpload.js
     import { LightningElement, track } from 'lwc';  
     import saveRecord from '@salesforce/apex/ContactController.saveContact';  
     import { NavigationMixin } from 'lightning/navigation';  
     import { ShowToastEvent } from 'lightning/platformShowToastEvent';  
     const MAX_FILE_SIZE = 100000000; //10mb  
     export default class NewRecordWithFileUpload extends NavigationMixin(LightningElement) {  
       @track name;  
       @track phone;  
       @track email;  
       @track description;  
       uploadedFiles = []; file; fileContents; fileReader; content; fileName  
       onNameChange(event) {  
         this.name = event.detail.value;  
       }  
       onPhoneChange(event) {  
         this.phone = event.detail.value;  
       }  
       onEmailChange(event) {  
         this.email = event.detail.value;  
       }  
       onDescriptionChange(event) {  
         this.description = event.detail.value;  
       }  
       onFileUpload(event) {  
         if (event.target.files.length > 0) {  
           this.uploadedFiles = event.target.files;  
           this.fileName = event.target.files[0].name;  
           this.file = this.uploadedFiles[0];  
           if (this.file.size > this.MAX_FILE_SIZE) {  
             alert("File Size Can not exceed" + MAX_FILE_SIZE);  
           }  
         }  
       }  
       saveContact() {  
         this.fileReader = new FileReader();  
         this.fileReader.onloadend = (() => {  
           this.fileContents = this.fileReader.result;  
           let base64 = 'base64,';  
           this.content = this.fileContents.indexOf(base64) + base64.length;  
           this.fileContents = this.fileContents.substring(this.content);  
           this.saveRecord();  
         });  
         this.fileReader.readAsDataURL(this.file);  
       }  
       saveRecord() {  
         var con = {  
           'sobjectType': 'Contact',  
           'LastName': this.name,  
           'Email': this.email,  
           'Phone': this.phone,  
           'Description': this.description  
         }  
         saveRecord({  
           contactRec: con,  
           file: encodeURIComponent(this.fileContents),  
           fileName: this.fileName  
         })  
           .then(conId => {  
             if (conId) {  
               this.dispatchEvent(  
                 new ShowToastEvent({  
                   title: 'Success',  
                   variant: 'success',  
                   message: 'Contact Successfully created',  
                 }),  
               );  
               this[NavigationMixin.Navigate]({  
                 type: 'standard__recordPage',  
                 attributes: {  
                   recordId: conId,  
                   objectApiName: 'Contact',  
                   actionName: 'view'  
                 },  
               });  
             }  
           }).catch(error => {  
             console.log('error ', error);  
           });  
       }  
     }  
    

    newRecordWithFileUpload.html
     <template>  
       <div class="slds-box slds-theme_default">  
         <div class="slds-m-around_medium">  
           <lightning-input type="text" label="Name" onchange={onNameChange}></lightning-input>  
           <lightning-input type="tel" label="Phone" onchange={onPhoneChange}></lightning-input>  
           <lightning-input type="email" label="Email" onchange={onEmailChange}></lightning-input>  
           <lightning-textarea name="input3" label="Description" onchange={onDescriptionChange}  
             placeholder="type here..."></lightning-textarea>  
           <lightning-input type="file" onchange={onFileUpload} required name="uploadFile" label="Upload File">  
           </lightning-input>  
         </div>  
         <div>  
           <center>  
           <lightning-button label="Save" onclick={saveContact}>  
           </lightning-button>  
           </center>  
         </div>  
       </div>  
     </template>  
    

    Step 3 : Add this File Upload Lightning Web Component to Lightning App Page

    Add this newRecordWithFileUpload LWC component to any lightning page.

    Output:



    Ps: on above example we did not add validations, make sure that add your own validations.