Browsing "Older Posts"

  • 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 Access Custom Label In LWC

    salesforcepoint Sunday, 8 November 2020
    How To Access Custom Label In LWC


    How to get Custom Label value in LWC (Lightning Web Components):

    Usage of Custom Label: We know that we use custom label for error messages, constants and storing values which are translated into specific language by using translation workbench.

    How to access Custom Label in LWC components

    For accessing custom label value we need to import it from salesforce/label module. check below.
    import labelName from '@salesforce/label/labelApiName';

    Example: Accessing custom label in lightning web component

    Create custom label in your org. Add Hello_World as Name and "Hellow World! Welcome to salesforcepoint.com" as Value

    customLabelLwc.js
    import { LightningElement } from 'lwc';
    //importing custom label to 'WELCOME_MESSAGE'
    import WELCOME_MESSAGE from '@salesforce/label/c.Hello_World';
    
    export default class CustomLabelLwc extends LightningElement {
        message = WELCOME_MESSAGE; //assigning WELCOME_MESSAGE value to "message" property
    }


    customLabelLwc.html
    <template>
        <div class="slds-box slds-theme_shade slds-align_absolute-center">
            <h1>{message}</h1>
        </div>
    </template>

    Output:

    How To Access Custom Label In LWC example
  • connectedCallBack() In LWC With Example

    salesforcepoint Thursday, 1 October 2020

    LWC connectedCallBack()

    connectedCallBack in Lwc


    This is one of the life cycle hooks in web component JavaScript. connectedCallBack function invokes/fires automatically when a certain lwc component is inserted into web dom. It works like an init handler in the lightning aura component, we can say it is lwc init handler. 

    Important Points  about ConnectedCallBack()

    • It flows from the parent to child component. I.e if the main component has inner component/child components then, ConnectedCallBack function on parent is invoked first, and then ConnectedCallBack of child lwc component will be fired.
    • In this function, we can access only host element i.e template. 
    • By using "this.template" we can access the host element.
    • It's invoked after the constructor hook fired.
    • If we want to fire any logic on component load (for example dispatching the event, assigning values to properties) then we should use ConnectedCallBack life cycle hook.

    Examples for connectedCallBack in LWC

    These are the basic example to understand connectedCallback function. 
    In this example, we need to display the list of contacts on the table. While the table is loading we have to show the spinner.

    AccountController

    public with sharing class AccountController {
        @AuraEnabled(cacheable=true)
        public static List<Account>  getAccountList(){
            return [SELECT Id, Name,Phone,Industry FROM Account order by createddate desc LIMIT 5];
        }
    }

    connectedCallbackLwc.html

    <template>
        <template if:true={isSpinner}>
            <div class="spinner">
                <lightning-spinner alternative-text="Loading" size="medium"></lightning-spinner>
            </div>
        </template>
        <lightning-card title="connectedCallback Example">
            <lightning-datatable data={accountList} columns={cols} key-field="Id">
            </lightning-datatable>
        </lightning-card>
    </template>

    connectedCallbackLwc.js

    import { LightningElement, wire, track } from 'lwc';
    import getLatestAccounts from '@salesforce/apex/AccountController.getAccountList';
    const COLS = [
        { label: 'Name', fieldName: 'Name', type: 'text' },
        { label: 'Stage', fieldName: 'Phone', type: 'text' },
        { label: 'Amount', fieldName: 'Industry', type: 'text' }
    ];
    export default class ConnectedCallbackLwc extends LightningElement {
        cols = COLS;
        @track isSpinner = false;
        @track accountList = [];
    
        connectedCallback() {
            this.isSpinner = true;
        }
    
        @wire(getLatestAccounts) fetchAccList(result) {
            this.isSpinner = false;
            if (result.data) {
                this.accountList = result.data;
                this.error = undefined;
            } else if (result.error) {
                this.error = result.error;
                this.accountList = [];
            }
        }
    }

    LWC connectedCallBack() Output:

    In above example, we make "isSpinner" equal to true in connectedCallback function, so that we will see spinner on the page load. Once page data loaded we turned off spinner by making "isSpinner" equal to false in fetchAccList wired function
  • How to align Lightning Button To Center, Right Or Left in LWC & Aura Components

    salesforcepoint Sunday, 20 September 2020

    Lightning Button Alignment

    In many cases we need button alignment to left, center or right. Event though we used correct slds classes, alignment will be not at expected position. In that cases we need to use "slds-clearfix" class for above div of the button, so that we can able to display lightning button at required place. 

    Slds CSS class for center alignment:  slds-align_absolute-center
    Slds CSS class for right alignment: slds-float_right
    Slds CSS class for left alignment: slds-float_left

    Button Alignment in LWC (Lightning Web Components)

    ButtonAlignmentInLwc.html
    <template>
        <div class="slds-clearfix">
            <lightning-button label="Left" class="slds-float_left"></lightning-button>
        </div>
        <div class="slds-clearfix">
            <lightning-button label="I am Center" class="slds-align_absolute-center"></lightning-button>
        </div>
        <div class="slds-clearfix">
            <lightning-button label="I am Right" class="slds-float_right"></lightning-button>
        </div>
    </template>

    Button Alignment In Lightning Aura Components:

    ButtonAlignmentInAura.cmp
    <aura:component >
        <div class="slds-clearfix">
            <lightning:button label="Left" class="slds-float_left"/>
        </div>
        <div class="slds-clearfix">
            <lightning:button label="I am Center" class="slds-align_absolute-center"/>
        </div>
        <div class="slds-clearfix">
            <lightning:button label="I am Right" class="slds-float_right"/>
        </div>
    </aura:component>

    Output

    Slds Lightning Button Alignment


  • Validate LWC Input Data: How To Add Validations In Input Form

    salesforcepoint Tuesday, 8 September 2020
    How To Add Validations In LWC Input Form

    Hello folks, in this post we will see how to add validations in lwc input form and showing error message upon button click (most probably Save operation). In any input form we need to validate user entered data before commuting to database whether it is a insert/ update.

    Example for Validate LWC Input Form Data: 

    In below example we are going to create Contact form that contains First Name, Last Name, phone, email. Here we need to add validations like Name, email should be mandatory.

    lwcValidateInputForm.html
    <template>  
        <div class="slds-box slds-theme_default">  
          <div class="slds-m-around_medium">  
            <lightning-input type="text" max-length=12 required label="Name" onchange={onNameChange}></lightning-input>  
            <lightning-input type="tel" label="Phone" onchange={onPhoneChange}></lightning-input>
            <lightning-input type="email" required label="Email" onchange={onEmailChange}></lightning-input>    
          </div>  
          <div>  
            <center>  
            <lightning-button label="Save" onclick={saveContact}>  
            </lightning-button>  
            </center>  
          </div>  
        </div>  
      </template>



    LwcValidateInputForm.js
    import { LightningElement, track } from 'lwc';
    export default class LwcValidateInputForm extends LightningElement {
        @track name;
        @track phone;
        @track email;
    
        onNameChange(event) {
            this.name = event.detail.value;
        }
        onPhoneChange(event) {
            this.phone = event.detail.value;
        }
        onEmailChange(event) {
            this.email = event.detail.value;
        }
    
        saveContact() {
            const isInputsCorrect = [...this.template.querySelectorAll('lightning-input')]
                .reduce((validSoFar, inputField) => {
                    inputField.reportValidity();
                    return validSoFar && inputField.checkValidity();
                }, true);
            if (isInputsCorrect) {
             //perform success logic
    
            }
        }
    }

    Output:

    If we need to make any field required then we need to mention "required" attribute in lightning-input tag so that we can show error message upon save button click. Once user click on save button, we are validating each filed by querying with the lightning-input. By using checkValidity() function we are checking each values entered in form. If all values are in required format then we can write further logic.

    If we don't want standard error message, we can set custom message with the help of below attributes.


    message-when-value-missing: Used for assigning custom error message when value missed on required field.
    message-when-too-short: Used for assigning custom error message when entered value not meeting expected length. For this we need to add one more attribute i.e min-length.
    message-when-too-long: Used for assigning custom error message when entered value exceeds expected length. For this we need to add one more attribute i.e max-length.
    message-when-pattern-mismatch: Used for assigning custom error message when entered value not matching the expected pattern. This is used for email, url, phone, password, text. For this we need to add one more attribute i.e "pattern".

    Reference: https://developer.salesforce.com/docs/component-library/bundle/lightning-input/specification
  • How to Use Safe Navigation Operator (?.) in Salesforce Apex | Winter 21 Release Notes

    salesforcepoint Monday, 31 August 2020

    How to Use the Safe Navigation Operator in Apex

    How to use Safe Navigation Operator in Apex Salesforce

    Hello guys, as part of salesforce winter 21 release, salesforce introduced Safe Navigation Operator( (?.) to avoid null pointer exceptions in apex. This is very useful feature for developers. If we need to check something (whether it is a object, map, list..) should not be null then we will write (?.) at the end.  If the left side of the expression(?.) is null, then right side is not evaluated and result will be null.

    Till now we used != null condition to check object is not null like below.

    if (object!= null){
       string s= object.fieldName;
    }

    we can write above code by using safe navigation operator like below
    string s= object?.fieldName;
    



    Example: In this example we have a accountIdAccountMap, it contains account id as key, account record as value. We need to get name of the account.

    string accountName = accountIdAccountMap.get(accId).Name; 
    // this will return null pointer exception if accId not available in the map.
    

    if account not exist on map we will get null pointer exception because we accessing null object for fetching name.

    Traditional approach to avoid above null pointer exception:

    if(accountIdAccountMap.get(accId) != null) {
     accountName = accountIdAccountMap.get(accId).Name;
    }

    OR
    if(accountIdAccountMap.containsKey(accId)) {
     accountName = accountIdAccountMap.get(accId).Name;
    }

    By using Safe Navigation operator:

    string Account Name = accountIdAccountMap.get(accId)?.Name;
    

    if we need to check whether map is not null then we can write

    accountIdAccountMap?.get(accId)?.Name;

  • LWC Combobox Picklist : Get Pick-list Values (With / Without Default Record Type Id)

    salesforcepoint Friday, 28 August 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
  • LWC refreshApex: How To Refresh Page Data in Lightning Web Component

    salesforcepoint Wednesday, 12 August 2020

    refreshApex in lwc: 

    refreshApex in Lightning Web Component Example

    In this post we are going to see how to use refreshApex() function in Lightning web Components with example. If we need to refresh lwc page data we should use refreshApex. We know that wire provisions data, if we use wire function or wire parameter to display data in front end, that data will not be changed or updated unless input parameters changed which are used in wire. By using refreshApex in lwc we can update wire function or wire parameter data, so that component values will be re-rendered.

    We need to import refreshApex function from salesforce/apex class, so that we can use it.

    refreshApex lwc example:


    In below example we are displaying latest five account records in lwc data table and we have a radio button to select the record. Once we click on Delete button selected record will be deleted from apex database but not on table. So we use refreshApex() function (refreshApex(this.wiredAccountList)) to fetch latest data from server on delete success in deleteRecord  function. We created "wiredAccountList" property to assign result of wire function "accList" and this property used in resfreshApex function.

    AccountController.cls

    public with sharing class AccountController {
        @AuraEnabled(cacheable=true)
        public static List<account>  getAccountList(){
            return [SELECT Id, Name,Phone,Industry FROM Account order by createddate desc LIMIT 5];
        }
    }


    lwcRefreshApex.js

    import { LightningElement, wire, track } from 'lwc';
    import { deleteRecord } from 'lightning/uiRecordApi';
    import { refreshApex } from '@salesforce/apex';
    
    import getLatestAccounts from '@salesforce/apex/AccountController.getAccountList';
    const COLS = [
      { label: 'Name', fieldName: 'Name', type: 'text' },
      { label: 'Stage', fieldName: 'Phone', type: 'text' },
      { label: 'Amount', fieldName: 'Industry', type: 'text' }
    ];
    export default class LwcRefreshApex extends LightningElement {
      cols = COLS;
      @track selectedRecord;
      @track accountList = [];
      @track error;
      @track wiredAccountList = [];
    
      @wire(getLatestAccounts) accList(result) {
        this.wiredAccountList = result;
    
        if (result.data) {
          this.accountList = result.data;
          this.error = undefined;
        } else if (result.error) {
          this.error = result.error;
          this.accountList = [];
        }
      }
    
      handelSelection(event) {
        if (event.detail.selectedRows.length > 0) {
          this.selectedRecord = event.detail.selectedRows[0].Id;
        }
      }
      deleteRecord() {
        deleteRecord(this.selectedRecord)
          .then(() => {
            refreshApex(this.wiredAccountList);
          })
          .catch(error => {
          })
      }
    }
    lwcRefreshApex.html

    <template>  
        <lightning-card title="Latest Five Accounts">  
          <lightning-button slot="actions" label="Delete Account" onclick={deleteRecord}></lightning-button>  
            <lightning-datatable  
            data={accountList} columns={cols} key-field="Id" 
            max-row-selection="1" onrowselection={handelSelection} >  
            </lightning-datatable>  
        </lightning-card>  
      </template>
    Output:

    LWC refreshApex() not working?



    Make sure that the input parameter in the refreshApex should be total result of wire function but not only data, i.e in many cases we return { error, data } in wire function and we use data only for refresh apex, in this case refreshApex will not work. We must entire result (check above example where we return result not { error, data } and that is assigned to one dummy variable i.e wiredAccountList and that is used as input parameter for refreshApex().
  • Pass Data/Values From Child LWC Component To Parent LWC Using Custom Event

    salesforcepoint Sunday, 9 August 2020

    How to Pass Values From Child to Parent component in LWC

    Pass Values data fromChild to Parent component in LWC example


    In this post we will see how to pass data from child to parent in Lwc. If we want to fire parent lightning web component function from child LWC component function when child function fired or if we need pass data from child LWC component to parent Lightning web component then we need to use custom events. Unlike aura component we don't to create separate event in lightning web components.

    Steps for child to parent communication in LWC:
    1. Define a custom event in child lightning web component.
    2. Add values (which needs to pass to parent lwc) to event. (optional)
    3. Dispatch the event.
    Example:

    const lwcEvent= new CustomEvent('eventname', {
       detail:{varible1:value, varible2 : value} 
      });
     this.dispatchEvent(lwcEvent);

    Here eventName is user defined key word for event, which is going to use in child component tag in parent component. Make sure that event name should not be starts with "on" word.
    4 . Handle event on parent lightning web component with the "oneventname" handler function. Here oneventname is the dispathed event in child component(see above code), 'on' should be added before event name.

    <c-child-lwc-component oneventName={handleEvent}></c-child-lwc-component>

    5. By using event.detail.variableName we will get value which is passed from child lwc.

    Example Scenario for Passing values from Child Lightning web component to Parent Lightning web component.

    In Below example we have a child component(lwcChild) where we are showing list of account records. In parent component(lwcParent) we are referring child component. on click of record in table, we are firing custom event and dispatching the event with selected account id and then we are showing details of respective account in parent component.

    AccountController.cls
    public with sharing class AccountController {
            @AuraEnabled(cacheable=true)
            public static List<account>  getAccountList(){
            return [SELECT Id, Name,Phone,Industry FROM Account WITH SECURITY_ENFORCED LIMIT 10];
        }
    }

    Create new lightning web component: lwcChild
    lwcChild.js


    import { LightningElement, api } from 'lwc';
    export default class LwcChild extends LightningElement {
        @api accountList;
        handleAccountClick(event) {
            let selectedAccId = event.currentTarget.getAttribute("data-key");
            //custom event
            const passEvent = new CustomEvent('accountselection', {
                detail:{recordId:selectedAccId} 
            });
           this.dispatchEvent(passEvent);
        }
    }

    lwcChild.html
    <template>
        <table class="slds-table slds-table_bordered">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Phone</th>
                    <th>Industry</th>
                </tr>
            </thead>
            <tbody>
                <template if:true={accountList}>
                    <template for:each={accountList} for:item="acc">
                        <tr key={acc.Id} data-key={acc.Id} onclick={handleAccountClick}>
                            <td>{acc.Name}</td>
                            <td>
                                <lightning-formatted-phone value={acc.Phone}></lightning-formatted-phone>
                            </td>
                            <td>{acc.Industry}</td>
                        </tr>
                    </template>
                </template>
            </tbody>
        </table>
    </template>
    Create new lightning web component: lwcParent
    lwcParent.js
    import { LightningElement,wire,track } from 'lwc';
    import getAccountList from '@salesforce/apex/AccountController.getAccountList';
    
    export default class LwcParent extends LightningElement {
        @track selectedAccountId;
        @wire(getAccountList) accountList;  
        onAccountSelection(event){
            this.selectedAccountId = event.detail.recordId;
        }
    }

    lwcParent.html
    <template>
        <div class="row">
    
            <div class="column" style="float: left; width: 70%; padding: 10px;">
                <div class="slds-box">
                    <template if:true={accountList.data}>
                        <c-lwc-child account-list={accountList.data} onaccountselection={onAccountSelection}></c-lwc-child>
                    </template>
                </div>
            </div>
    
            <div class="column" style="float: right; width: 30%; padding: 10px;">
                    <div class="slds-box">
                        <div slot="actions">
                            <div class="slds-box">
                                Selected Account Information
                            </div>
                        </div>
                        <lightning-record-view-form record-id={selectedAccountId} object-api-name="Account">
                            <div class="slds-box slds-them_shade">
                                <lightning-output-field field-name="Name"></lightning-output-field>
                                <lightning-output-field field-name="Phone"></lightning-output-field>
                                <lightning-output-field field-name="Industry"></lightning-output-field>
                            </div>
                        </lightning-record-view-form>
                    </div>
                </div>
        </div>
    </template>

    Output


  • 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[j].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" };
  • 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: