Dependent Picklist in LWC

Today i am going to share how to create a field dependency in LWC component.

We are using Custom fields on Account that are Upsell(UpsellOpportunity__c) and SLA(SLA__c). We created the field dependency on Object level using these field as shown in image below.

So now we are all set to work LWC Component:

Html:

<template>
    <lightning-combobox name="Upsell"
                        label="Upsell"
                        placeholder="Select Upsell"
                        options={upsellOptions}
                        onchange={handleUpsellChange}>
    </lightning-combobox>
    <lightning-combobox name="Sla"
                        label="Sla"
                        placeholder="Select Sla"
                        options={slaOptions}>
    </lightning-combobox>
</template>

JS

import { LightningElement,wire, api, track  } from 'lwc';

import {getObjectInfo} from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import {getPicklistValues} from 'lightning/uiObjectInfoApi';
import SLA_FIELD from '@salesforce/schema/Account.SLA__c';
import UPSELL_FIELD from '@salesforce/schema/Account.UpsellOpportunity__c';

export default class Testdependentpicklist extends LightningElement {
    @wire(getObjectInfo, {objectApiName: ACCOUNT_OBJECT })
    accountInfo;

    @track slaOptions;
    @track upsellOptions;

    @wire(getPicklistValues, {recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: SLA_FIELD })
    slaFieldInfo({ data, error }) {
        if (data) this.slaFieldData = data;
    }
    @wire(getPicklistValues, {recordTypeId:'$accountInfo.data.defaultRecordTypeId', fieldApiName: UPSELL_FIELD })
    upsellFieldInfo({ data, error }) {
        if (data) this.upsellOptions = data.values;
    }
    handleUpsellChange(event) {
        let key = this.slaFieldData.controllerValues[event.target.value];
        this.slaOptions = this.slaFieldData.values.filter(opt => opt.validFor.includes(key));
    }
}

XML File :

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

Working Demo:

Please have a look and let me know the feedbacks .

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s