LWC Dependent Pick List Example
An example of working with Salesforce Dependant Picklists in LWC using the uiObjectInfoApi. The juicy bit is in the method setDependentPicklist
on line 61 of countrySateSelector.js.
<template> | |
<lightning-combobox | |
label="Country" | |
name="country" | |
value={country} | |
options={countryCodes} | |
onchange={handleCountryChange}> | |
</lightning-combobox> | |
<template if:true={showStates}> | |
<lightning-combobox | |
label="State/Province" | |
name="state" | |
value={state} | |
options={stateCodeOptions} | |
onchange={handleChange}> | |
</lightning-combobox> | |
</template> | |
</template> |
import { LightningElement, wire } from "lwc"; | |
import { getObjectInfo, getPicklistValues } from "lightning/uiObjectInfoApi"; | |
import Contact from "@salesforce/schema/Contact"; | |
import MailingStateCode from "@salesforce/schema/Contact.MailingStateCode"; | |
import MailingCountryCode from "@salesforce/schema/Contact.MailingCountryCode"; | |
const DefaultCountryCode = "US"; | |
export default class X7SAdtalemAddressForm extends LightningElement { | |
country = DefaultCountryCode; | |
state; | |
@wire(getObjectInfo, { objectApiName: Contact }) | |
contactObject; | |
@wire(getPicklistValues, { | |
recordTypeId: "$contactObject.data.defaultRecordTypeId", | |
fieldApiName: MailingCountryCode | |
}) | |
countryCodesWire({ data, error }) { | |
if (data) { | |
this.countryCodes = [...data.values]; | |
} | |
} | |
@wire(getPicklistValues, { | |
recordTypeId: "$contactObject.data.defaultRecordTypeId", | |
fieldApiName: MailingStateCode | |
}) | |
stateCodes; | |
/** | |
* Show/Hide state picklist based on options and selected country. | |
* @returns {boolean} | |
*/ | |
get showStates() { | |
return !!( | |
this.stateCodeOptions && | |
this.stateCodeOptions.length > 0 && | |
this.country | |
); | |
} | |
/** | |
* Get dependent state picklist values when country is selected. | |
* @returns {Array} | |
*/ | |
get stateCodeOptions() { | |
if (this.stateCodes && this.stateCodes.data && this.country) { | |
return this.setDependentPicklist(this.stateCodes.data, this.country); | |
} | |
} | |
/** | |
* Get values for dependent picklists | |
* @param {Object} data - Wire data | |
* @param controllerValue - Value from controlling picklist. | |
* @returns {Array} | |
*/ | |
setDependentPicklist(data, controllerValue) { | |
const key = data.controllerValues[controllerValue]; | |
return data.values.filter((opt) => opt.validFor.includes(key)); | |
} | |
/** | |
* Change the country and reset the state value. | |
* @param event | |
*/ | |
handleCountryChange(event) { | |
this.country = event.target.value; | |
this.state = undefined; | |
} | |
/** | |
* Change event that updates its corresponding reactive value. | |
* @param event | |
*/ | |
handleChange(event) { | |
this[event.target.name] = event.target.value; | |
} | |
} |