Latest Posts

Lightning Web Components

Lightning Aura Components

Apex

Recent Posts

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

  • Call Lightning Web Component in Quick Action Salesforce

    salesforcepoint Tuesday 27 December 2022

     Lightning Web Component in Quick Action

    In this post, we will see how to add or show a Lightning web component in salesforce quick actions. When salesforce introduced LWC first time,  LWC in quick action was not available, that time we encapsulated LWC component on Aura component and achieved this. But as part of the Salesforce summer release, they introduced this feature.

    Add LWC in Quick Action

    Define Component Metadata in the Configuration .xml File

    In targets, add lightning__RecordAction as a target to designate the Lightning web component as a quick action on a record page.
    Add a targetConfig and set targets to lightning__RecordAction.
    Set actionType to ScreenAction.

    Example  for LWC as Quick Action

    Create a new LWC component: lwcQuickAction

    lwcQuickAction.xml
    <lightningcomponentbundle xmlns="http://soap.sforce.com/2006/04/metadata">
        <apiversion>55.0</apiversion>
        <isexposed>true</isexposed>
       <targets>
           <target>lightning__RecordAction</target>
       </targets>
        <targetconfigs>
       <targetconfig targets="lightning__RecordAction">
         <actiontype>ScreenAction</actiontype>
       </targetconfig>
     </targetconfigs>
    </lightningcomponentbundle>
      
    lwcQuickAction.js
    import { LightningElement, api, wire } from 'lwc';
    import { CloseActionScreenEvent } from 'lightning/actions';
    
    export default class LwcQuickAction extends LightningElement {
        @api recordId;
        @api objectApiName;
    
        handleCancel(event) {
            // Add your cancel button implementation here
            this.dispatchEvent(new CloseActionScreenEvent());
         }
    }
          
     
    lwcQuickAction.html
    <template>
        <lightning-quick-action-panel header="Test LWC Quick Action">
            <p>This is Test LWC component in quick action</p>
            <div slot="footer">
                <lightning-button variant="neutral" label="Cancel" onclick={handleCancel}></lightning-button>
            </div>
        </lightning-quick-action-panel>
    </template>
      

    If we want to display a standard header and footer then we can use "lightning-quick-action-panel" tag. For closing the quick action on a custom button click, we need to import "CloseActionScreenEvent" from 'lightning/actions' and dispatch that in an event.

    Output:

    Call Lightning Web Component in Quick Action Salesforce


  • How to get RecordTypeId Based On RecordType Name In Apex Salesforce

    salesforcepoint Saturday 16 October 2021

    Get RecordTypeId Based On RecordType Name In Apex

    Get RecordTypeId Based On RecordType Name In Apex


    In many use cases, we need to check recordtype conditions in apex logic. Below is the same peace of code that gives recordtypeId of given sobject name and recordType label.

    
      String egRecordTypeID = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Record Type Label').getRecordTypeId();
      

    Here we need to provide Sobject name in place of  "Case" and recordType label in place of "Record Type Label"
  • disconnectedCallback () in LWC with example

    salesforcepoint Thursday 1 July 2021
    disconnectedCallback in LWC with Example


     What is disconnectedCallback(): 

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

    When disconnectedCallback() fired?

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

    Also Check: connectedCallback() LWC with example.

    disconnectedCallback() in LWC Example

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


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

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

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

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

    Output
  • How to display Toast messages in LWC

    salesforcepoint Friday 8 January 2021

     How to display Toast messages in Lightning Web Components

    How to display Toast messages in LWC

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

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

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

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



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

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

    Output of Show Toast Message Notifications in LWC :

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

    salesforcepoint Sunday 3 January 2021

    Get Record Id dynamically in LWC

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

     How To Fetch Current Record Id In Lightning Web component Example


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

    Output: Add above ligtning web component to any of the record page(Ex: Account, contact, opportunity....)
    How to get current record id in Lightning Web Component
  • How to pass values from child to parent lightning aura component with Component Event

    salesforcepoint Wednesday 23 December 2020

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

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


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

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

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

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

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

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

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

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

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

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

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

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

    Output

  • How To Access Custom Label In LWC

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


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

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

    How to access Custom Label in LWC components

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

    Example: Accessing custom label in lightning web component

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

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


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

    Output:

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

    salesforcepoint Thursday 1 October 2020

    LWC connectedCallBack()

    connectedCallBack in Lwc


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

    Important Points  about ConnectedCallBack()

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

    Examples for connectedCallBack in LWC

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

    AccountController

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

    connectedCallbackLwc.html

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

    connectedCallbackLwc.js

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

    LWC connectedCallBack() Output:

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

    salesforcepoint Sunday 20 September 2020

    Lightning Button Alignment

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

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

    Button Alignment in LWC (Lightning Web Components)

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

    Button Alignment In Lightning Aura Components:

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

    Output

    Slds Lightning Button Alignment


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

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

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

    Example for Validate LWC Input Form Data: 

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

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



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

    Output:

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

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


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

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

    salesforcepoint Monday 31 August 2020

    How to Use the Safe Navigation Operator in Apex

    How to use Safe Navigation Operator in Apex Salesforce

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

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

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

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



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

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

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

    Traditional approach to avoid above null pointer exception:

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

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

    By using Safe Navigation operator:

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

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

    accountIdAccountMap?.get(accId)?.Name;

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

    salesforcepoint Friday 28 August 2020

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

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

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

    Get picklist values based on recordtypeId In Salesforce LWC component


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

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

    Output LWC picklist values based on recordtype values

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

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

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


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

    salesforcepoint Wednesday 12 August 2020

    refreshApex in lwc: 

    refreshApex in Lightning Web Component Example

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

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

    refreshApex lwc example:


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

    AccountController.cls

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


    lwcRefreshApex.js

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

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

    LWC refreshApex() not working?



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

    salesforcepoint Sunday 9 August 2020

    How to Pass Values From Child to Parent component in LWC

    Pass Values data fromChild to Parent component in LWC example


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

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

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

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

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

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

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

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

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

    Create new lightning web component: lwcChild
    lwcChild.js


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

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

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

    Output