Get picklist values Dynamically (Apex, VF and LWC)

Get picklist values dynamically in Lightning web component

Apex controller

 public class GetPicklistFieldValuesDynamicController {

    @AuraEnabled (Cacheable=true)
    public static List<PicklistSet> GetPicklistFieldValues(String objectName, String fieldName)   {
    Schema.SObjectType objectType =   getSObjectTypeFromObjectName(objectName);
    Schema.DescribeSObjectResult result =   objectType.getDescribe();
    Map<String, Schema.SObjectField> fields = result.fields.getMap();
    Schema.DescribeFieldResult fieldResult = fields.get(fieldName).getDescribe();
    List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
    List<PicklistSet> picklistValues = new List<PicklistSet>();
    for (Schema.PicklistEntry picklistVal : ple) {
        PicklistSet tempPicklist = new PicklistSet(picklistVal.getLabel(), picklistVal.getValue());
            picklistValues.add(tempPicklist);
    }
        return picklistValues;
    }

    public static SObjectType getSObjectTypeFromObjectName(String objectName) {
       return ((SObject) Type.forName('Schema', objectName).newInstance()).getSObjectType();
    }

    public class PicklistSet {
        @AuraEnabled public String label { get; set; }
        @AuraEnabled public String value { get; set; }

        public PicklistSet(String label, String value){
            this.label = label;
            this.value = value;
        }
    }

}

Lightning web component

//GetPicklistFieldValuesDynamic.html
<template>
    <lightning-card>
        <div class="slds-p-around_medium">
            <lightning-combobox
                    name="progress"
                    label="Options"
                    value={value}
                    options={picklistFieldValues}
                    onchange={handleChange} >
            </lightning-combobox>
            <p>Selected value is: {value}</p>
        </div>
    </lightning-card>
</template>


//GetPicklistFieldValuesDynamic.js
import { LightningElement, api, wire, track} from 'lwc';
import getPicklistFieldValues from '@salesforce/apex/GetPicklistFieldValuesDynamicController.GetPicklistFieldValues';

export default class GetPicklistFieldValuesDynamic extends LightningElement {
    @api recordId;
    @track objectApiName = 'Account';
    @track fieldApiName = 'Industry';
    @track picklistFieldValues = [];
    @track value = '';

    connectedCallback(){
       this.fetchPicklistFields();
    }

    fetchPicklistFields() {
        getPicklistFieldValues({
          objectName : this.objectApiName,
          fieldName : this.fieldApiName,
      })
      .then((result) => {
          console.log('fetchPicklistFields');
          this.picklistFieldValues = [
             {
                 "label": "--None--",
                 "value": ""
             },
             ...result
         ];
         console.log(this.picklistFieldValues);
      })
      .catch((error) => {
         console.error(error);
      });
    }

    handleChange(event) {
        this.value = event.detail.value;
    }
    
}

//Metadata
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>59.0</apiVersion>
    <description>Get Picklist Field Values Dynamic</description>
    <isExposed>true</isExposed>
    <masterLabel>Get Picklist Field Values Dynamic</masterLabel>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

Output

Get picklist values dynamically in VisualForce

Apex controller

public class GetPicklistFieldValuesDynamicController {
    public String selectedPicklistValue { get; set; }
    public List<SelectOption> picklistFieldValues { get; set; }

    public GetPicklistFieldValuesDynamicController(){
        String objectName = 'Account';
        String fieldName = 'Industry';
        picklistFieldValues =  getPicklistValues(objectName,fieldName);
    }

    public List<SelectOption> getPicklistValues(String objectName, String fieldName) {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('', '--None--'));

        Schema.DescribeFieldResult fieldResult = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap().get(fieldName).getDescribe();

        List<Schema.PicklistEntry> picklistValues = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry entry : picklistValues) {
            options.add(new SelectOption(entry.getValue(), entry.getLabel()));
        }
        return options;
    }
}

VisualForce

<apex:page id="GetPicklistFieldValuesDynamic" controller="GetPicklistFieldValuesDynamicController">
    <apex:form>
        <apex:pageBlock title="Picklist Value">
            <apex:pageBlockSection>
                <apex:pageBlockSectionItem>
                    <apex:outputLabel value="Select Picklist Value" for="picklistValue"/>
                    <apex:selectList value="{!selectedPicklistValue}" size="1">
                        <apex:selectOptions value="{!picklistFieldValues}"/>
                        <apex:actionSupport event="onchange" reRender="selectedValueDisplay"/>
                    </apex:selectList>
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem>
                    <apex:outputText value="Selected Value: " />
                    <apex:outputText id="selectedValueDisplay" value="{!selectedPicklistValue}"/>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output

Useful Links

https://developer.salesforce.com/blogs/developer-relations/2008/12/using-the-metadata-api-to-retrieve-picklist-values


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Index