Skip to content

Instantly share code, notes, and snippets.

@megasmack
Last active October 17, 2024 12:39
Show Gist options
  • Save megasmack/8e60d139b023057741ff09ee7d9cf9ec to your computer and use it in GitHub Desktop.
Save megasmack/8e60d139b023057741ff09ee7d9cf9ec to your computer and use it in GitHub Desktop.
LWC Dependent Pick List Example

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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment