June 4, 2021

Dynamic Picklist using lightning combobox in Lightning Web Component in Salesforce

Sample Code:
 
HTML:
<template>
    <lightning-card>
        <div style="width:200px; padding:0.5rem;">
            <lightning-combobox
                name="filter"
                label="Industry"
                value={selectedValue}
                options={options}
                onchange={handlePicklistChange}
                placeholder="Select Industry">
            </lightning-combobox>
        </div>
    </lightning-card>
</template>

JavaScript:
import { LightningElement, wire } from 'lwc';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
import { getPicklistValues, getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

export default class SampleLWC extends LightningElement {

    options = [];
    picklistOptions = [];
    selectedValue;

    @wire( getObjectInfo, { objectApiName: ACCOUNT_OBJECT } )
    objectInfo;

    @wire( getPicklistValues, { recordTypeId: '$objectInfo.data.defaultRecordTypeId', fieldApiName: INDUSTRY_FIELD } )
    wiredData( { error, data } ) {

        console.log( 'Inside Get Picklist Values' );

        if ( data ) {
                            
            console.log( 'Data received from Picklist Field ' + JSON.stringify( data.values ) );
            this.options = data.values.map( objPL => {
                return {
                    label: `${objPL.label}`,
                    value: `${objPL.value}`
                };
            });
            console.log( 'Options are ' + JSON.stringify( this.options ) );

        } else if ( error ) {

            console.error( JSON.stringify( error ) );

        }

    }

    handlePicklistChange( event ) {
        
        console.log( 'New Value selected is ' + JSON.stringify( event.detail.value ) );   

    }

}

Output:
 
 

No comments:

Post a Comment