Browsing "Older Posts"

Browsing Category "Lightning Web Components"
  • Resolving the Issue: Ensuring Invocation of LWC Wire Function When Properties Are Undefined

    salesforcepoint Wednesday, 24 January 2024

    Navigating the intricacies of Apex calls within the Lightning Web Components (LWC) framework often involves careful consideration of input properties. When employing the wire decorator to facilitate Apex calls with multiple input properties, encountering the scenario where one of these properties is undefined can pose a challenge. The consequence is a failure to trigger the intended Apex call, hindering the expected flow of data.

    The Challenge:

    In a typical LWC setup, the wire decorator enables seamless communication between the client-side component and the server-side Apex controller. However, when dealing with multiple input properties, dependencies between them can become critical. This becomes especially apparent when certain properties rely on data fetched from another wire service, such as the getRecord service.


    Consider a example scenario where the accountId and contactId properties are integral to an wire Apex call, and their values are dependent on data obtained from a getRecord wire service. While successfully populating one of these properties with the received data, it becomes apparent that the second wire service fails to trigger when the property is undefined.

    How to Resolve:

    A straightforward resolution to this challenge involves proactively addressing undefined properties. By assigning blank values to properties that might initially be undefined, you create a more robust and predictable flow for your Apex calls.


    Here's a closer look at the solution in action:


     @wire(getRecord, { recordId: '$recordId' })
    wiredRecord({ error, data }) {
        if (data) {
            // Process data and populate properties
            this.accountId = data.fields.AccountId.value || ''; // Assigning a blank value if undefined
            this.contactId = data.fields.ContactId.value || ''; // Assigning a blank value if undefined
        } else if (error) {
            // Handle error
            console.error('Error fetching record:', error);
        }
    }
    
    @wire(triggerApexCall, { accountId: '$accountId', contactId: '$contactId' })
    wiredApexCall({ error, data }) {
        if (data) {
            // Process data from the Apex call
            console.log('Received data from Apex call:', data);
        } else if (error) {
            // Handle error
            console.error('Error in Apex call:', error);
        }
    }
    

    By adopting this approach, you ensure that both properties, accountId and contactId, are consistently defined before triggering the subsequent Apex call. This not only resolves the issue but also promotes a more reliable and resilient architecture within your Lightning Web Components. Conclusion: Understanding the nuances of data flow and dependency management in LWC is essential for building robust and effective components. Addressing challenges like the one discussed here not only resolves immediate issues but also contributes to a more maintainable and scalable codebase. By proactively handling undefined properties, you enhance the predictability of your Apex calls, fostering a smoother user experience in your Lightning Web Components.

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


  • 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" };
  • 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:
  • 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:

  • LWC Custom File Upload Component Along With New Record Creation

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

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

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

    ContactController


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

    Step 2: Create Lightning Web Component 

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

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

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

    Add this newRecordWithFileUpload LWC component to any lightning page.

    Output:



    Ps: on above example we did not add validations, make sure that add your own validations.
  • How To Add Hyper Link For Name Column In lightning-datatable in LWC

    salesforcepoint Tuesday, 23 June 2020

    Lightning Web Component (LWC) Examples: Add Hyper Link Url For Name Column/Field In lightning Data Table Example

    Hello guys, in this post we are  going to see how to add hyper link url for lwc data table. As we know that if we use lightning-datatable tag we can show list of records data in table. But for name field if we use type:"text" we can't show clickable hyper link for record name on lightning Data Table. If we want display any field or column with link we need to make some tweaks on data what we are going to display on table. So that we can show link and once we click on that it will takes you to respective record page. Check below example code.

    Hyper Link For Name field In lightning-datatable in LWC:



    Create apex class: OpportunityController

     public with sharing class OpportunityController {  
       @AuraEnabled(cacheable=true)  
       public static List<opportunity> fetchOpportunityList(){  
         return [SELECT Id, Name, StageName,Amount From Opportunity LIMIT 100];  
       }  
     }  
    

    Create Lightning Web Component with name lwcDataTableHyperLink:

    lwcDataTableHyperLink.js

     import { LightningElement, wire, track } from "lwc";  
     import getOpportunities from "@salesforce/apex/OpportunityController.fetchOpportunityList";  
     const COLS = [  
      {  
       label: "Name",  
       fieldName: "recordLink",  
       type: "url",  
       typeAttributes: { label: { fieldName: "Name" }, tooltip:"Name", target: "_blank" }  
      },  
      { label: "Stage", fieldName: "StageName", type: "text" },  
      { label: "Amount", fieldName: "Amount", type: "currency" }  
     ];  
     export default class LwcDataTableHyperLink extends LightningElement {  
      cols = COLS;  
      error;  
      @track oppList = [];  
      @wire(getOpportunities)  
      getOppList({ error, data }) {  
       if (data) {  
        var tempOppList = [];  
        for (var i = 0; i < data.length; i++) {  
         let tempRecord = Object.assign({}, data[i]); //cloning object  
         tempRecord.recordLink = "/" + tempRecord.Id;  
         tempOppList.push(tempRecord);  
        }  
        this.oppList = tempOppList;  
        this.error = undefined;  
       } else if (error) {  
        this.error = error;  
        this.oppList = undefined;  
       }  
      }  
     }  
    
    If we see above code we are not assigning wire function data directly to oppList property, instead we are modifying every record to assign link for Name column (tempRecord.recordLink = "/" + tempRecord.Id;).

    lwcDataTableHyperLink.html

     <template>  
       <lightning-card title="Data Table In LWC">  
         <div class="slds-box">  
           <lightning-datatable  
           data={oppList} columns={cols} key-field="Id">  
           </lightning-datatable>  
         </div>  
       </lightning-card>  
     </template>  
    

    Output:

     <aura:application extends="force:slds">  
       <c:lwcDataTableHyperLink/>  
     </aura:application>