Tag Archives: LWC

LWC Navigate Record Detail Page To New Browser Tab

import { LightningElement, track } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class TestComponent extends NavigationMixin(LightningElement) {

    @track accountId = '0018G00000KsFcJQAV';

    handlenavigateToAccountViewPage(event) {
        this[NavigationMixin.GenerateUrl]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.accountId,
                objectApiName: 'Account',
                actionName: 'view'
            }
        }).then(generatedUrl => {
            window.open(generatedUrl);
        });
    }
}

Lightning Web Component(LWC) Toast Messages

A component can send a toast notification that pops up to alert users of a success, error, or warning. A toast can also simply provide information. To display a toast notification in Lightning Experience or Lightning communities, import ShowToastEvent from the lightning/platformShowToastEvent module. Here is the example to show Lightning Web Component(LWC) Toast Messages.

Toast Event Properties:

Parameter Type Description
title String (Required) The title of the toast, displayed as a heading.
message String (Required) A string representing the body of the message. It can contain placeholders in the form of {0} ... {N}. The placeholders are replaced with the links on messageData.
messageData String[] or Object url and label values that replace the {index} placeholders in the message string.
variant String Changes the appearance of the notice. Toasts inherit styling from toasts in the Lightning Design System. Valid values are: info (default), success, warning, and error.
mode String Determines how persistent the toast is. Valid values are: dismissable (default), remains visible until you click the close button or 3 seconds has elapsed, whichever comes first; pester, remains visible for 3 seconds and disappears automatically. No close button is provided; sticky, remains visible until you click the close button.

LWCToastMessage.html:

<template>
    <lightning-button label="Success" onclick={showSuccess}></lightning-button>&nbsp;
    <lightning-button label="Error" onclick={showError}></lightning-button>&nbsp;
    <lightning-button label="Warning" onclick={showWarning}></lightning-button>&nbsp;
    <lightning-button label="Information" onclick={showInfo}></lightning-button>&nbsp;
</template>

LWCToastMessage.js:

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class LWCToastMessages extends LightningElement {

    showError() {
        const evt = new ShowToastEvent({
            title: 'Error',
            message: 'This is an error message',
            variant: 'error',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }

    showSuccess(){
        const evt = new ShowToastEvent({
            title: 'Success',
            message: 'This is a success message',
            variant: 'success',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }

    showWarning(){
        const evt = new ShowToastEvent({
            title: 'Warning',
            message: 'This is a warning message',
            variant: 'warning',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }

    showInfo() {
        const evt = new ShowToastEvent({
            title: 'Info',
            message: 'This is an information message',
            variant: 'info',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
}

LWCToastMessage.js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets> 
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>




Salesforce LWC Custom Datatable Pagination

Apex Class:

public class AccountController {
    
    @AuraEnabled//Get Account Records
    public static String getAccountList(Integer pageSize, Integer pageNumber){
        String jsonDT = '';
        
        //Offset for SOQL
        Integer offset = (pageNumber - 1) * pageSize;
        
        //Total Records
        Integer totalRecords = [SELECT COUNT() FROM Account];
        Integer recordEnd = pageSize * pageNumber;
        
        AccountDTWrapper objDT =  new AccountDTWrapper();  
        objDT.pageSize = pageSize;
        objDT.pageNumber = pageNumber;
        objDT.recordStart = offset + 1;
        objDT.recordEnd = totalRecords >= recordEnd ? recordEnd : totalRecords;
        objDT.totalRecords = totalRecords;
        objDT.accounts = [SELECT Id, Name, AccountNumber, Industry, Phone FROM Account LIMIT :pageSize OFFSET :offset];
        jsonDT = JSON.serialize(objDT);
        return jsonDT;
    }
    
    public class AccountDTWrapper {
        public Integer pageSize {get;set;}
        public Integer pageNumber {get;set;}
        public Integer totalRecords {get;set;}
        public Integer recordStart {get;set;}
        public Integer recordEnd {get;set;}
        public List<Account> accounts {get;set;}
    }
}

accountList.html

<template>
    <template if:true={loader}>
        <lightning-spinner alternative-text="Loading..." size="small"></lightning-spinner>
    </template>

    <div class="slds-box slds-theme_default">
        <lightning-card  title="Accounts">
            <table class="slds-table slds-table_cell-buffer slds-table_bordered">
                <thead>
                    <tr class="slds-line-height_reset slds-text-title_caps">
                        <th  class="slds-is-resizable" scope="col">
                            <div class="slds-truncate" title="Name">
                                Name
                            </div>
                        </th>
                        <th  class="slds-is-resizable" scope="col">
                            <div class="slds-truncate" title="Account Number">
                                Account Number
                            </div>
                        </th>
                        <th  class="slds-is-resizable" scope="col">
                            <div class="slds-truncate" title="Industry">
                                Industry
                            </div>
                        </th>
                        <th class="slds-is-resizable" scope="col">
                            <div class="slds-truncate" title="Phone">
                                Phone
                            </div>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <template if:true={accounts}>
                        <template for:each={accounts} for:item="acc">
                            <tr key={acc.Id}>
                                <th scope="row" data-label="Name">
                                    <div class="slds-truncate" title={acc.Name}>{acc.Name}</div>
                                </th>
                                <th scope="row" data-label="Account Number">
                                    <div class="slds-truncate" title={acc.AccountNumber}>{acc.AccountNumber}</div>
                                </th>
                                <th scope="row" data-label="Industry">
                                    <div class="slds-truncate" title={acc.Industry}>{acc.Industry}</div>
                                </th>
                                <th scope="row" data-label="Phone">
                                    <template if:true={acc.Phone}>
                                    <div class="slds-truncate" title={acc.Phone}>{acc.Phone}</div>
                                </template>
                                </th>
                            </tr>
                        </template>
                    </template>
                </tbody>
            </table>
            <template if:true={isDisplayNoRecords}>
                <div class="slds-align_absolute-center">
                    <br/>
                    No records found
                </div>
            </template>
            <br/>
            <div class="slds-align_absolute-center"> 
                <div class="slds-p-right_xx-small">
                        
                    <lightning-button label="Prev"
                    disabled={isPrev} onclick={handlePrev}
                                        variant="brand"
                                        icon-name="utility:back"
                                        name="prev"></lightning-button>  
                </div>
                <span class="slds-badge slds-badge_lightest">
                    {recordStart}-{recordEnd} of {totalRecords} | Page {pageNumber} of {totalPages}
                </span>
                <div class="slds-p-left_xx-small">
                    <lightning-button label="Next"
                    disabled={isNext} onclick={handleNext}
                                        variant="brand"
                                        icon-name="utility:forward"
                                        icon-position="right"
                                        name="next"></lightning-button>
                </div>
            </div>  
        </lightning-card>
    </div>
</template>

accountList.js

import { LightningElement, wire, api, track  } from 'lwc';
import getAccountList from '@salesforce/apex/AccountController.getAccountList';

export default class AccountList extends LightningElement {
    @track loader = false;
    @track error = null;
    @track pageSize = 10;
    @track pageNumber = 1;
    @track totalRecords = 0;
    @track totalPages = 0;
    @track recordEnd = 0;
    @track recordStart = 0;
    @track isPrev = true;
    @track isNext = true;
    @track accounts = [];

    //On load
    connectedCallback() {
        this.getAccounts();
    }

    //handle next
    handleNext(){
        this.pageNumber = this.pageNumber+1;
        this.getAccounts();
    }

    //handle prev
    handlePrev(){
        this.pageNumber = this.pageNumber-1;
        this.getAccounts();
    }

    //get accounts
    getAccounts(){
        this.loader = true;
        getAccountList({pageSize: this.pageSize, pageNumber : this.pageNumber})
        .then(result => {
            this.loader = false;
            if(result){
                var resultData = JSON.parse(result);
                this.accounts = resultData.accounts;
                this.pageNumber = resultData.pageNumber;
                this.totalRecords = resultData.totalRecords;
                this.recordStart = resultData.recordStart;
                this.recordEnd = resultData.recordEnd;
                this.totalPages = Math.ceil(resultData.totalRecords / this.pageSize);
                this.isNext = (this.pageNumber == this.totalPages || this.totalPages == 0);
                this.isPrev = (this.pageNumber == 1 || this.totalRecords < this.pageSize);
            }
        })
        .catch(error => {
            this.loader = false;
            this.error = error;
        });
    }

    //display no records
    get isDisplayNoRecords() {
        var isDisplay = true;
        if(this.accounts){
            if(this.accounts.length == 0){
                isDisplay = true;
            }else{
                isDisplay = false;
            }
        }
        return isDisplay;
    }
}

accountList.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
   <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

LWC Multi Step Wizard

Biswajeet   September 29, 2020   No Comments on LWC Multi Step Wizard

LWCWizard.html

<template>
    <lightning-progress-indicator current-step={currentStep} type="base" variant="base">
        <lightning-progress-step label="Step 1" value="1" onclick={handleOnStepClick}></lightning-progress-step>
        <lightning-progress-step label="Step 2" value="2" onclick={handleOnStepClick}></lightning-progress-step>
        <lightning-progress-step label="Step 3" value="3" onclick={handleOnStepClick}></lightning-progress-step>
    </lightning-progress-indicator>
    
    <template if:true={isStepOne}>
        <div>
            Step 1
        </div>
    </template>
    <template if:true={isStepTwo}>
        <div>
            Step 2
        </div>
    </template>
    <template if:true={isStepThree}>
        <div>
            Step 3
        </div>
    </template>
    
    <template if:true={isEnablePrev}>
        <lightning-button variant="base" label="Back" onclick={handlePrev}></lightning-button>
    </template>
    
    <template if:true={isEnableNext}>
        <lightning-button label="Next" variant="brand" onclick={handleNext}></lightning-button>
    </template>
    <template if:true={isEnableFinish}>
        <lightning-button label="Finish" variant="brand" onclick={handleFinish}></lightning-button>
    </template>
</template>

LWCWizard.js

import { LightningElement, track} from 'lwc';

export default class LWCWizard extends LightningElement {

    @track currentStep = '1';

    handleOnStepClick(event) {
        this.currentStep = event.target.value;
    }

    get isStepOne() {
        return this.currentStep === "1";
    }

    get isStepTwo() {
        return this.currentStep === "2";
    }

    get isStepThree() {
        return this.currentStep === "3";
    }

    get isEnableNext() {
        return this.currentStep != "3";
    }

    get isEnablePrev() {
        return this.currentStep != "1";
    }

    get isEnableFinish() {
        return this.currentStep === "3";
    }

    handleNext(){
        if(this.currentStep == "1"){
            this.currentStep = "2";
        }
        else if(this.currentStep = "2"){
            this.currentStep = "3";
        }
    }

    handlePrev(){
        if(this.currentStep == "3"){
            this.currentStep = "2";
        }
        else if(this.currentStep = "2"){
            this.currentStep = "1";
        }
    }

    handleFinish(){

    }
}

To create “base” style progress indicator you have need to add type="base" attribute in your lightning-progress-indicator tag in lightning component.

To create “path” style progress indicator you have need to add type="path" attribute in your lightning-progress-indicator tag in lightning component.