How to get Picklist field API and Label both in Apex

Published by

on


This requirement can be achieved using Schema class. PFB one example UtilityClass which will return the API to Label mapping.

public without sharing class UtilityClass {
    //Generic Method to return picklist api to label map
    public static map<string, string> getPicklistField(String objectName, String fieldName){
        //picklist api to label map
        map<string, string> picklistValueMap = new map<string, string>();        
        // Get the SObjectField reference
        SObjectField field = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap().get(fieldName);        
        // Get the picklist values and labels
        List<Schema.PicklistEntry> picklistValues = field.getDescribe().getPicklistValues();
        //build the map
        for (Schema.PicklistEntry entry : picklistValues) {
            String label = entry.getLabel();
            String apiValue = entry.getValue();
            System.debug('Label: ' + label + ', API Value: ' + apiValue);
            picklistValueMap.put(apiValue, label);
        }
        system.debug('picklistValueMap>>'+picklistValueMap);
        return picklistValueMap;
    }
    
}

PFB the Output: