Latest Posts

LWC

Lightning Aura Components

Apex

Recent Posts

  • 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
  • How to pass values from child to parent lightning aura component with Component Event

    salesforcepoint Wednesday, 23 December 2020

     How to pass  Data from child lightning aura component to parent lightning aura component & Fire Parent component function from child component function

    How to Pass Data From Child Lightning Aura Component to Parent Lightning Aura Component


    If we need to pass values from child aura component to parent, we can't pass directly, for that we need to create custom lightning event.

    Steps for child to parent aura component communication:
     1. First we need to create custom Component event with required attributes (for passing values from child to parent). eg: compEvent

    2. We need to register event on child component using  <aura:registerEvent>.
    examle:
    <aura:registerEvent name="sampleComponentEvent" type="c:compEvent"/>

    3. Fire an Event: Fire an Event when some event occurs on child component(Eg: Button onclick, onchange of Input Text...).
    Example:
    var compEvent = component.getEvent("sampleComponentEvent");
             compEvent.setParams({"message" : "Static Text" });
             compEvent.fire();

    4. We need to handle event on Parent Component. Handler name and registerEvent name should be same. We can invoke function with the help of "action" attribute.
    Example:
        <aura:handler name="sampleComponentEvent" event="c:compEvent"
            action="{!c.handleComponentEvent}"/>

    When the child function gets fired, it calls custom event and pass required parameter’s. After that event invokes Handler method on Parent component(Eg: handleComponentEvent). By using " event.getParam("eventAttributeName"); " we can retrieve values that are passed to custom event.

    Example: Fire Parent Lightning Aura Component function from Child component and pass parameters.

    compEvent (component Event):
    <aura:event type="COMPONENT">
        <aura:attribute name="message" type="String"/>
    </aura:event>

    childComponentCmp
    
      <aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome" access="global" >
        <aura:attribute name="enteredText" type="String"/>
        <aura:registerEvent name="sampleComponentEvent" type="c:compEvent"/>
        
        <div class="slds-box slds-p-around_medium">
            <h2>This is Child Component</h2>
            <lightning:input label="Enter Name" aura:id="name" value ="{!v.enteredText}" />
            <lightning:button class="slds-m-top_small" variant="brand" label="Pass Value To Parent" title="Click Here" onclick="{! c.handleClick }"/>
        </div>
    </aura:component>
      

    childComponentCmpController.js
    
      ({
        handleClick : function(component, event, helper) {
            var compEvent = component.getEvent("sampleComponentEvent");
            compEvent.setParams({
                "message" : component.get("v.enteredText") 
            });
            compEvent.fire();
        }
    })
      

    ParentComponentCmp
    
      <aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome" access="global" >
        <aura:attribute name="enteredValue" type="String" />
        <aura:handler name="sampleComponentEvent" event="c:compEvent" action="{!c.handleComponentEvent}"/>
        
        <c:childComponentCmp/><br /><br />
        <div class="slds-box slds-p-around_medium">
            <h2>This is Parent Component</h2>
            value entered on child component input Box: <b>{!v.enteredValue}</b>
        </div>
    </aura:component>
      

    ParentComponentCmpController.js
    
      ({
        handleComponentEvent : function(component, event, helper) {
            var valueFromChild = event.getParam("message");
            alert(valueFromChild)
            component.set("v.enteredValue", valueFromChild);
        }
    })
      

    Output

  • How To Access Custom Label In LWC

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


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

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

    How to access Custom Label in LWC components

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

    Example: Accessing custom label in lightning web component

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

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


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

    Output:

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

    salesforcepoint Thursday, 1 October 2020

    LWC connectedCallBack()

    connectedCallBack in Lwc


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

    Important Points  about ConnectedCallBack()

    • It is flows from parent to child component. I.e if main component has inner component/child components then, ConnectedCallBack function on parent 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 host element.
    • It's invoked after constructor hook fired.
    • If we want fire any logic on component load (example dispatching 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 list of contacts on table. While table is loading we have to show 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" equals to true in connectedCallback function, so that we will see spinner on page load. Once page data loaded we turned off spinner by making "isSpinner" equals to false in fetchAccList wired function
  • How to align Lightning Button To Center, Right Or Left in LWC & Aura Components

    salesforcepoint Sunday, 20 September 2020

    Lightning Button Alignment

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

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

    Button Alignment in LWC (Lightning Web Components)

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

    Button Alignment In Lightning Aura Components:

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

    Output

    Slds Lightning Button Alignment


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

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

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

    Example for Validate LWC Input Form Data: 

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

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



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

    Output:

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

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


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

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

    salesforcepoint Monday, 31 August 2020

    How to Use the Safe Navigation Operator in Apex

    How to use Safe Navigation Operator in Apex Salesforce

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

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

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

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



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

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

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

    Traditional approach to avoid above null pointer exception:

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

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

    By using Safe Navigation operator:

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

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

    accountIdAccountMap?.get(accId)?.Name;

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

    salesforcepoint Friday, 28 August 2020

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

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

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

    Get picklist values based on recordtypeId In Salesforce LWC component


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

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

    Output LWC picklist values based on recordtype values

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

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

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


    Outut: LWC picklist values based on recordtype
  • LWC refreshApex: How To Refresh Page Data in Lightning Web Component

    salesforcepoint Wednesday, 12 August 2020

    refreshApex in lwc: 

    refreshApex in Lightning Web Component Example

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

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

    refreshApex lwc example:


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

    AccountController.cls

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


    lwcRefreshApex.js

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

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

    LWC refreshApex() not working?



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

    salesforcepoint Sunday, 9 August 2020

    How to Pass Values From Child to Parent component in LWC

    Pass Values data fromChild to Parent component in LWC example


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

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

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

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

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

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

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

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

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

    Create new lightning web component: lwcChild
    lwcChild.js


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

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

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

    Output


  • Salesforce Lightning Web Components - LWC Interview Questions

    salesforcepoint Monday, 3 August 2020

    Latest LWC Interview Questions 

    Latest LWC Interview Questions

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

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

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

    salesforcepoint Sunday, 2 August 2020

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

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

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

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

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

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

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

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

    salesforcepoint Saturday, 1 August 2020

    Display [Object Object] As String In JavaScript: 

    Display Object as String in JavaScript

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

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

    Example:  Display Object as String in js

    var cObj = { name: "Salesforec", age: 10, city: "CA" };
    console.log("cObj===>"+cObj ); //output : cObj===>"+[Object Object]
    console.log("cObj in String Format===>"+JSON.stringify(cObj) );
    // output: cObj in String Format===> { name: "Salesforec", age: 10, city: "CA" };
  • How To Get Record Id From aura:iteration In Lightning Component

    salesforcepoint Sunday, 26 July 2020

    Fetch Selected Record Id From Iteration Lightning Aura Component:




    If we need to fetch record id or some element from aura:iteration we can use html property dataset. By using this html dataset attributes we can pass id from component to JavaScript function when some event occurs. The name of a custom data element starts with data-. By using html elements, we can get not only id but we can get any element that we set for data element (ex: data-id, data-name) in lightning component.

    Example code for fetching record id in aura iteration:

    In below example we are fetching all the student records, In aura iteration  for div element we added data-id ="{!student.Id}". on click on student we are passing selected student id to JavaScript function handleSelect by using event.target.dataset.id. If we need to pass other attribute then we can create new data attribute, for example if we need to pass name of selected student then we add new attribute data-name and in js function we can get that attribute by using event.target.dataset.name.

    StudentController.cls
     public class StudentController {  
       @AuraEnabled  
       public static List<Student__c> getStudentList() {  
         List<Student__c> studentList = [SELECT Id, Name FROM Student__c];  
         return studentList;  
       }  
     }  
    

    StudentList.cmp
     <aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,  
                   flexipage:availableForRecordHome,force:hasRecordId,  
                   force:lightningQuickAction" controller="StudentController"  
             access="global" >  
       <aura:attribute name="studentList" type="List" />  
       <aura:handler name="init" action="{!c.fetchStudentList}" value="{!this}" />  
       <aura:iteration items="{!v.studentList}" var="student">  
         <div data-id ="{!student.Id}" class="slds-box slds-theme_shade" onclick="{!c.handleSelect}">  
           {!student.Name}  
         </div>  
       </aura:iteration>  
     </aura:component>  
    

    StudentListController.js
     ({  
       fetchStudentList : function(component, event, helper) {  
         var action = component.get("c.getStudentList");  
         action.setCallback(this, function(response) {  
           var state = response.getState();  
           if(state === 'SUCCESS') {  
             var studentList = response.getReturnValue();  
             component.set("v.studentList",studentList);  
           }  
           else {  
             alert('Error in getting data');  
           }  
         });  
         $A.enqueueAction(action);  
       },  
       handleSelect: function(component, event, helper) {  
         var selectedId = event.target.dataset.id;  
         alert(selectedId)  
       }  
     })  
    


    Output: