Display Picklist on frontend using Lightning Aura

Picklist field allow users to select value from defined list. To display picklist values at frontend first need
to fetch values from server side or apex controller. getDescribe() method from SObjectFieldClass which
returns Schema.DescribeFieldResult. It contains various methods like getLabel(), getName() and many
other. Among all of them getPicklistValues() is use to retrieve picklist values which return list of Picklist Entry objects.

getDescribe() & getPicklistValues()

Schema.DescribeFieldResult describeField = Account.AccountSource.getDescribe();
List<Schema.PicklistEntry> picklistEntries = describeField.getPicklistValues();
System.debug('***picklistEntries*** '+picklistEntries);

Result

11:28:51:005 USER_DEBUG [4]|DEBUG|***picklistEntries*** (Schema.PicklistEntry[getLabel=Web;getValue=Web;isActive=true;isDefaultValue=false;], Schema.PicklistEntry[getLabel=Phone Inquiry;getValue=Phone Inquiry;isActive=true;isDefaultValue=false;], Schema.PicklistEntry[getLabel=Partner Referral;getValue=Partner Referral;isActive=true;isDefaultValue=false;], Schema.PicklistEntry[getLabel=Purchased List;getValue=Purchased List;isActive=true;isDefaultValue=false;], Schema.PicklistEntry[getLabel=Other;getValue=Other;isActive=true;isDefaultValue=false;])

picklistEntries is a list of Schema.PicklistEntry object return from field describe result using getPicklistValues() method. Below are the instances method for PicklistEntry Object.

  • getLabel() : return display name of picklist value.
  • getValue() : return API name of picklist value.
  • isActive(): return true if picklist value is active.
  • isDefaultValue(): return true if picklist value is default value for picklist. Only one picklist value can be default value.

Source Code

Apex

public class DemoPicklistController {
    @AuraEnabled
    public static Map<String,String> getPicklistDetails(){
        try{
           return Utility.getPicklistDetails(Account.AccountSource.getDescribe());
        }
        catch(Exception ex){
            System.debug('Exception: ' + ex.getMessage() + 'on Line Number: '+ex.getLineNumber()+'Stack: '+ex.getStackTraceString());
            throw new AuraHandledException('Exception: ' + ex.getMessage() + 'on Line Number: '+ex.getLineNumber());
        }
    }
}

As we know , there is a limit on apex characters. Hence, to increase reusability of code write method in separate class and call them whenever needed.

public class Utility {
    public static Map<String,String> getPicklistDetails(Schema.DescribeFieldResult fieldDescription){
        try{
            Map<String,String> labelVsValueMapForPicklist = new Map<String,String>();
            List<Schema.PicklistEntry> picklistEntries = fieldDescription.getPicklistValues();
            for(Schema.PicklistEntry pEntry : picklistEntries){
                labelVsValueMapForPicklist.put(pEntry.getLabel(),pEntry.getValue());
            }
            return labelVsValueMapForPicklist;
        }
        catch(Exception ex){
            System.debug('Exception: ' + ex.getMessage() + 'on Line Number: '+ex.getLineNumber()+'Stack: '+ex.getStackTraceString());
            throw new AuraHandledException('Exception: ' + ex.getMessage() + 'on Line: '+ex.getLineNumber());
        }
    }
}

Lightning Component

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" controller="DemoPicklistController">
    <aura:attribute name="accountSourcePicklistMap" type="Map" access="global"/>
    <aura:attribute name="acc" type="sObject" default="{ 'sobjectType': 'Account' }" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
        <lightning:select name="accountSource" label="Account Source" value="{!v.acc.AccountSource}">
            <aura:if isTrue="{!v.accountSourcePicklistMap.length > 0}">
                <option value="">--Select--</option>
            </aura:if>
            <aura:iteration items="{!v.accountSourcePicklistMap}" var="val">
                <option text="{!val.label}" value="{!val.value}" selected="{!val.value == v.acc.AccountSource}"></option>
            </aura:iteration>
        </lightning:select>
</aura:component>

Controller

({
    doInit : function(component, event, helper) {
        helper.getPicklistValues(component, event, helper);
    }
})

Helper

({
    getPicklistValues : function(component, event, helper) {
        var action = component.get("c.getPicklistDetails");
        action.setCallback(this, function(res){
             var state = res.getState();
            if(state === "SUCCESS"){
                var result = res.getReturnValue();
                if(!$A.util.isEmpty(result) &amp;&amp; !$A.util.isUndefinedOrNull(result)){
                    var accountSourcePicklistMap = [];
                    for(var label in result){
                        accountSourcePicklistMap.push({label: label,value:result[label]});
                    }
                }
                component.set("v.accountSourcePicklistMap",accountSourcePicklistMap);
            }
            else if(state === "ERROR"){
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        // log the error passed in to AuraHandledException
                        console.log("Error message: " + errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });
        $A.enqueueAction(action);
    }
})

How to fetch picklist values dynamically ?

Create a generic method which will accept two arguments one is field name and other one is object name. In this method, getGlobalDescribe() method is used which will return map of all sObject names to all sObject tokens.

public static Map<String,String> fetchPicklistValues(String objName, String fieldName){
        Map<String,String> picklistValues = new Map<String,String>();
        if(Schema.getGlobalDescribe().containsKey(objName)){
            if(Schema.getGlobalDescribe().get(objName).getDescribe().fields.getMap().containsKey(fieldName)){
                Schema.DescribeFieldResult fieldDescription = Schema.getGlobalDescribe().get(objName).getDescribe().fields.getMAp().get(fieldName).getDescribe();
                for(Schema.PicklistEntry p : fieldDescription.getPicklistValues()){
                    picklistValues.put(p.getLabel(), p.getValue());
                }
            }
        }
        return picklistValues;
    }

You may also like...

Leave a Reply

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