ship
SalesForce Simplified

Your Go-To Resource for Streamlined Solutions and Expert Guidance

mountains
Empower Your Business
Dive deep into the world of CRM excellence, where innovation meets practicality, and transform your Salesforce experience with Forceshark's comprehensive resources

How to Retrieve All Picklist Values in Apex with Ease

Introduction

In Salesforce development, there are scenarios where you need to dynamically retrieve all the picklist values associated with a specific field. This could be useful in scenarios where you want to populate a dropdown dynamically or perform dynamic logic based on the available picklist options. In this article, we'll explore an Apex class that simplifies the process of fetching all picklist values with ease.

Apex class to retrieve picklist values

Now, let's craft an Apex class that will serve as a valuable tool for effortlessly retrieving picklist values. Stay tuned for a concise and effective solution in the upcoming code example.

public with sharing class FSRK_PicklistValueFetcher {
    public static Map<String, PicklistEntry> getPicklistEntryMap(String objectName, String fieldName) {
        SObjectType sObjectType = Schema.getGlobalDescribe().get(objectName);
        Map<String, SObjectField> fieldMap = sObjectType.getDescribe().fields.getMap();
        SObjectField sObjectField = fieldMap.get(fieldName);

        return getPicklistEntryMap(sObjectType, sObjectField);
    }

    public static Map<String, PicklistEntry> getPicklistEntryMap(SObjectType sObjectType, SObjectField sObjectField) {
        Map<String, PicklistEntry> picklistEntryMap = new Map<String, PicklistEntry>();

        Map<String, SObjectField> fieldMap = sObjectType.getDescribe().fields.getMap() ;
        DescribeFieldResult fieldResult = fieldMap.get(sObjectField.getDescribe().getName()).getDescribe();
        for (PicklistEntry pe : fieldResult.getPicklistValues()) {
            picklistEntryMap.put(pe.getLabel(), pe);
        }
        return picklistEntryMap;
    }
}

How to Dynamically Query All Picklist Values

To dynamically query all picklist values using the provided Apex class, follow these steps:

Invoke the Method

String objectName = 'Account';
String fieldName = 'Type';
Map<String, PicklistEntry> picklistValues = FSRK_PicklistValueFetcher.getPicklistEntryMap(objectName, fieldName);

Utilize the Result

The picklistValues map now contains all the picklist values for the specified object and field, where the labels serve as keys.

Conclusion

Effortlessly retrieving all picklist values in Apex is a critical functionality for dynamic Salesforce development. The FSRK_PicklistValueFetcher class presented here simplifies the process, providing an easy-to-use solution for developers seeking to enhance the flexibility and dynamism of their Salesforce applications.