Skip to main content
I have problem in fetching state based on country selected in picklist.

1.I have configured default state and country picklist .

2.implemented a apex method to fetch states and country but not able map state based on country selected since i am using custom object.

Can please anyone help me to resolve this?

 
15 个回答
  1. 2025年1月20日 12:10

    I was able to achieve this with LWC, I am not sure if this is any relevant. Adding the comment for future references. Most of the code are already available in the internet.

    <template>

    <template lwc:if={picklistValues.data}>

    <lightning-combobox name="country" label="Country" value={selectedCountry} placeholder="Select Country" options={picklistValues.data.values} onchange={handleCountry}> </lightning-combobox>

    <lightning-combobox name="state" label="State" value={selectedState} placeholder="Select State" options={states} onchange={handleState}> </lightning-combobox>

    </template>

    </template>

     

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

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

    import COUNTRY_CODE from '@salesforce/schema/User.CountryCode';

    import STATE_CODE from '@salesforce/schema/User.StateCode';

    import USER_OBJECT from '@salesforce/schema/User';

    export default class CountryStateTest extends LightningElement {

    selectedCountry;

    selectedState;

    countryToStates;

    states;

    @wire(getObjectInfo, { objectApiName: USER_OBJECT })

    objectInfo;

    @wire(getPicklistValues, {

    recordTypeId: '012000000000000AAA',//This is the sfddc default recordtype for this function as per documentation

    fieldApiName: COUNTRY_CODE

    })

    picklistValues;

    @wire(getPicklistValues, { recordTypeId: '012000000000000AAA', fieldApiName: STATE_CODE })

    wiredStates({ data }) {

    if (!data) {

    return;

    }

    const validForNumberToCountry = Object.fromEntries(Object.entries(data.controllerValues).map(([key, value]) => [value, key]));

    this.countryToStates = data.values.reduce((accumulatedStates, state) => {

    const countryIsoCode = validForNumberToCountry[state.validFor[0]];

    return { ...accumulatedStates, [countryIsoCode]: [...(accumulatedStates?.[countryIsoCode] || []), state] };

    }, {});

    }

    handleCountry(e) {

    this.selectedCountry = e.detail.value;

    console.log(`Country ${this.selectedCountry} event ${JSON.stringify(e)}`);

    this.states = this.countryToStates[this.selectedCountry] || [];

    }

    handleState(e) {

    this.selectedState = e.detail.value;

    console.log(`State ${this.selectedState}`);

    }

    }

0/9000