Browsing "Older Posts"

Browsing Category "Lightning Web Components Basics"
  • disconnectedCallback () in LWC with example

    salesforcepoint Thursday, 1 July 2021
    disconnectedCallback in LWC with Example


     What is disconnectedCallback(): 

    The disconnectedCallback() is one of the life cycle functions of modern web components. 

    When disconnectedCallback() fired?

    It gets invoked automatically when the corresponding web component gets removed from DOM. If we need to perform any logic when the component is removed from DOM, that logic can be added in disconnectedCallback(). This hook flows from Parent component to child. We use disconnectedCallback() to purging caches or removing event listeners that are created on connectedCallback().

    Also Check: connectedCallback() LWC with example.

    disconnectedCallback() in LWC Example

    In this example, we have two components. Those are 'disconnectedCallbackParentLwc' and 'disconnectedCallbackChildLwc'. Here disconnectedCallbackChildLwc referred in parent component. In the parent component, we have a button 'Show/Hide' to show and hiding the child component. Initially, the child component displayed, once users click on the button 'disconnectedCallbackChildLwc' the child component removed from DOM. Since the component getting removed from DOM, disconnectedCallback function on the child component gets invoked and an alert will appear.


    disConnectedCallbackChildLwc.js
    import { LightningElement } from 'lwc';
    export default class DisConnectedCallbackChildLwc extends LightningElement {
        disconnectedCallback() {
            console.log('child disconnected callback')
        }
    }

    disConnectedCallbackChildLwc.html
    <template>
        <p>I am child LWC component</p>
    </template> 

    disConnectedCallbackParentLwc.js
    import { LightningElement } from 'lwc';
    export default class DisConnectedCallbackParentLwc extends LightningElement {
        show = true;
        handleShowHide() {
            this.show = !this.show;
        }
    }

    disConnectedCallbackParentLwc.html
    <template>
        <lightning-card title="disconnectedCallback Example">
            <p>Parent LWC component</p>
            <lightning-button variant="brand" slot="actions" label="Show/Hide" onclick={handleShowHide}
                class="slds-m-left_x-small"></lightning-button>
            <template if:true={show}>
                <c-dis-connected-callback-child-lwc></c-dis-connected-callback-child-lwc>
            </template>
        </lightning-card>
    </template>

    Output
  • How to display Toast messages in LWC

    salesforcepoint Friday, 8 January 2021

     How to display Toast messages in Lightning Web Components

    How to display Toast messages in LWC

    A lightning web component can send a toast notification that can be inform users of a success, error, or warning information. If we want to show a toast message notification in Lightning Experience or Lightning communities, then we need to import ShowToastEvent function from the lightning/platformShowToastEvent module. So that we can create ShowToastEvent in the function wherever we want. ShowToastEvent contains title, message, messageData, variant, mode parameters.

    title: It is String attribute. Used for showing title of the toast and displayed as a heading.
    message: It is a String attribute. It is used for showing message in the toast.
    variant: It is a String attribute. It controls theme and icon displayed in the toast notification. We can give Success, Info, Error Warning values based on requirement.
    mode: It is a string to define how toast notification should persistent. Valid values: sticky, pester, dismissable .
    • sticky: If we use this, toast notification will not be closed automatically, user need to click on  close button to close toast notification.
    • dismissable: it's a default value. If we use this, user can see close button & toast notification closed automatically after 3 seconds.
    • pester: If we use this option, toast notification closed automatically after 3 seconds & user can't see close button.

    Example:  Show Toast messages in Lightning Web Components(LWC)

    In below example we have four buttons, I.e Success, Info, Warning, Error. When particular button click event happens, we are dispatching ShowToastEvent event in the corresponding functions. 



    lwcShowToast.js
    
    import { LightningElement } from 'lwc';
    import { ShowToastEvent } from 'lightning/platformShowToastEvent';
    
    export default class LwcShowToast extends LightningElement {
        //Sample Success Toast message code
        showSuccessNotification() {
            const evt = new ShowToastEvent({
                title: "Success",
                message: "This is sample success message",
                variant: "success",
            });
            this.dispatchEvent(evt);
        }
        
        //Sample code for showing error message in Toast
        showErrorNotification() {
            const evt = new ShowToastEvent({
                title: "Error",
                message: "This is sample error message",
                variant: "error",
            });
            this.dispatchEvent(evt);
        }
    
        //Sample code for showing warning message in Toast
        showWarningNotification() {
            const evt = new ShowToastEvent({
                title: "Warning",
                message: "This is sample warning message",
                variant: "warning",
                mode: "sticky"
            });
            this.dispatchEvent(evt);
        }
    
        //Sample code for showing Info message in Toast
        showInfoNotification() {
            const evt = new ShowToastEvent({
                title: "Info",
                message: "This is sample info message",
                variant: "info",
                mode: "pester"
            });
    
            this.dispatchEvent(evt);
        }
    }
    

    lwcShowToast.js
    
    <template>
        <lightning-card title="Toast Messages" icon-name="custom:custom19">
            <div class="slds-p-around_medium">
                <lightning-button variant="success" label="Show Success" onclick={showSuccessNotification}></lightning-button>
                <lightning-button variant="destructive" label="Show Error" onclick={showErrorNotification}></lightning-button>
                <lightning-button variant="destructive-text" label="Show Warning" onclick={showWarningNotification}></lightning-button>
                <lightning-button label="Show Info" onclick={showInfoNotification}></lightning-button>
            </div>
        </lightning-card>
    </template>
    

    Output of Show Toast Message Notifications in LWC :

  • How To Get Current Record Id In LWC (Lightning Web components)

    salesforcepoint Sunday, 3 January 2021

    Get Record Id dynamically in LWC

    How To Get Current Record Id In LWC -Lightning Web components Example
    In many scenarios we need to have current record id in the lightning web component. Id we want get current record id then we need to define "recordId" prublic property in corresponding lwc component JavaScript file and the lightning web component should be added into lightning record page.

     How To Fetch Current Record Id In Lightning Web component Example


    lwcGetRecordId.js
    
    import { LightningElement, api } from 'lwc';
    export default class LwcGetRecordId extends LightningElement {
        @api recordId;
    }
    
    lwcGetRecordId.html
    
    <template>
        Current Record Id : {recordId}
    </template>
    

    Output: Add above ligtning web component to any of the record page(Ex: Account, contact, opportunity....)
    How to get current record id in Lightning Web Component
  • 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


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

    salesforcepoint Sunday, 26 July 2020

    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:
  • LWC Modal: How To Create/Show Modal Popup in LWC

    salesforcepoint Saturday, 25 July 2020

    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: