Saturday, October 26, 2019

Custom Dependent Picklist Field in Salesforce using Lightning Web Components

This post explains how to implement custom dependent picklist field using lightning web components(lwc)



To get the picklist values in lightning web components we can use 'getPicklistValues' or 'getPicklistValuesByRecordType' wire adapters, these wire adapters uses the lightning/uiObjectInfoApi scoped module to get the picklist values based on specific Field or based on Record Type.

Syntax

import { getPicklistValues, getPicklistValuesByRecordType } from 'lightning/uiObjectInfoApi';

For the demo, I created two fields on Account.
Controlling Field(picklist): Account Country
Dependent Field(picklist): Account State

The structure of the dependent field


HTML Code
<template>
    <lightning-card title="Custom Dependent Picklist using Lightning Web Components"><br/>
        <div class="slds-grid slds-gutters" style="margin-left:3%">
            <div class="slds-col slds-size_1-of-4">
                <lightning-combobox label="Account Country" 
                                    name="country" 
                                    onchange={handleCountryChange} 
                                    options={controllingValues} 
                                    placeholder="--None--" 
                                    value={selectedCountry}></lightning-combobox><br/>
                
                <div if:true={selectedCountry}>
                    Selected Country: <b>{selectedCountry}</b>
                </div>
            </div>
            <div class="slds-col slds-size_1-of-4">
                <lightning-combobox label="Account State" 
                                    name="state"
                                    onchange={handleStateChange} 
                                    options={dependentValues} 
                                    placeholder="--None--" 
                                    value={selectedState}
                                    disabled={isEmpty}></lightning-combobox><br/>
                <div if:true={selectedState}>
                    Selected State: <b>{selectedState}</b>
                </div>
            </div>
        </div><br/>

        <div if:true={error}>
            <p>{error}</p>
        </div>
    </lightning-card>
</template>

Javascript Controller Code
import { LightningElement, wire, track } from 'lwc';
import { getPicklistValuesByRecordType } from 'lightning/uiObjectInfoApi';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

export default class DependentPickListInLWC extends LightningElement {

    // Reactive variables
    @track controllingValues = [];
    @track dependentValues = [];
    @track selectedCountry;
    @track selectedState;
    @track isEmpty = false;
    @track error;
    controlValues;
    totalDependentValues = [];

    // Account object info
    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
    objectInfo;

    // Picklist values based on record type
    @wire(getPicklistValuesByRecordType, { objectApiName: ACCOUNT_OBJECT, recordTypeId: '$objectInfo.data.defaultRecordTypeId'})
    countryPicklistValues({error, data}) {
        if(data) {
            this.error = null;

            let countyOptions = [{label:'--None--', value:'--None--'}];

            // Account Country Control Field Picklist values
            data.picklistFieldValues.Account_Country__c.values.forEach(key => {
                countyOptions.push({
                    label : key.label,
                    value: key.value
                })
            });

            this.controllingValues = countyOptions;

            let stateOptions = [{label:'--None--', value:'--None--'}];

             // Account State Control Field Picklist values
            this.controlValues = data.picklistFieldValues.Account_State__c.controllerValues;
            // Account State dependent Field Picklist values
            this.totalDependentValues = data.picklistFieldValues.Account_State__c.values;

            this.totalDependentValues.forEach(key => {
                stateOptions.push({
                    label : key.label,
                    value: key.value
                })
            });

            this.dependentValues = stateOptions;
        }
        else if(error) {
            this.error = JSON.stringify(error);
        }
    }

    handleCountryChange(event) {
        // Selected Country Value
        this.selectedCountry = event.target.value;
        this.isEmpty = false;
        let dependValues = [];

        if(this.selectedCountry) {
            // if Selected country is none returns nothing
            if(this.selectedCountry === '--None--') {
                this.isEmpty = true;
                dependValues = [{label:'--None--', value:'--None--'}];
                this.selectedCountry = null;
                this.selectedState = null;
                return;
            }

            // filter the total dependent values based on selected country value 
            this.totalDependentValues.forEach(conValues => {
                if(conValues.validFor[0] === this.controlValues[this.selectedCountry]) {
                    dependValues.push({
                        label: conValues.label,
                        value: conValues.value
                    })
                }
            })

            this.dependentValues = dependValues;
        }
    }

    handleStateChange(event) {
        this.selectedState = event.target.value;
    }
}

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

You can also find the code on Github
GitHub Link


Result

Monday, October 21, 2019

How to get Current Logged in User information in Lightning Web Component(lwc)

This post explains how to get logged in user information in lightning web components(lwc)



check below post how to import current user id in lightning web components
https://www.salesforcecodecrack.com/2019/01/how-to-import-current-user-id.html

To get the record details to use the getRecord wire adapter from 'lightning/uiRecordApi' scope module.
Syntax
import { getRecord } from 'lightning/uiRecordApi';

HTML code
<template>
    <lightning-card title="Current Logged User Information">
        <template if:true={objUser}>
            <dl class="slds-list_horizontal slds-wrap" style="margin-left: 3%;">
                <dt class="slds-item_label slds-truncate" title="First Name">First Name:</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objUser.FirstName}</b></dd>
                <dt class="slds-item_label slds-truncate" title="Last Name">Last Name:</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objUser.LastName}</b></dd>
                <dt class="slds-item_label slds-truncate" title="Full Name">Name:</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objUser.Name}</b></dd>
                <dt class="slds-item_label slds-truncate" title="Alias">Alias:</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objUser.Alias}</b></dd>
                <dt class="slds-item_label slds-truncate" title="Active">Is Active:</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objUser.IsActive}</b></dd>
            </dl>
        </template>
    </lightning-card>
</template>

Javascript Controller 
import { LightningElement, track, wire} from 'lwc';

// importing to get the record details based on record id
import { getRecord } from 'lightning/uiRecordApi';

// impoting USER id
import USER_ID from '@salesforce/user/Id'; 

export default class CurrentUserDetailsInLWC extends LightningElement {

    @track objUser = {};
    
    // using wire service getting current user data
    @wire(getRecord, { recordId: USER_ID, fields: ['User.FirstName', 'User.LastName', 'User.Name', 'User.Alias', 'User.IsActive'] })
    userData({error, data}) {
        if(data) {
            window.console.log('data ====> '+JSON.stringify(data));

            let objCurrentData = data.fields;

            this.objUser = {
                FirstName : objCurrentData.FirstName.value,
                LastName : objCurrentData.LastName.value,
                Name : objCurrentData.Name.value,
                Alias : objCurrentData.Alias.value,
                IsActive : objCurrentData.IsActive.value,
            }
        } 
        else if(error) {
            window.console.log('error ====> '+JSON.stringify(error))
        } 
    }

}

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

Result

Saturday, October 19, 2019

How to test salesforce performance and speed in Lightning Experience

If your Users are experiencing slow page-loading times when using Lightning Experience, it may be related to one or more of the following issue types.
  • Geographical
  • Device
  • Browser
  • Salesforce organization configuration issues

It is a simple online tool to measure your browser Javascript speed and your internet connection speed to Salesforce’s servers. 

How to access the tool?

To access this tool simply log-on to your Salesforce org and remove everything after “[your domain name].lightning.force.com/” in the browser URL and add the speedtest.jsp 
Ex:
https://<your domain>.lightning.force.com/speedtest.jsp
OR
https://[instance].salesforce.com/speedtest.jsp


Click the "Test Speed" button, tool tests all the performances, Once the test is finished, results will be displayed.

Reference
https://help.salesforce.com/articleView?id=000316034&language=en_US&type=1&mode=1