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 {
/**
* Retrieves a Map of PicklistEntry values for a given object and field name.
* @param objectName The API name of the object.
* @param fieldName The API name of the field.
* @return Map A map containing picklist values with their labels as keys.
*/
public static Map getPicklistEntryMap(String objectName, String fieldName) {
SObjectType sObjectType = Schema.getGlobalDescribe().get(objectName);
Map fieldMap = sObjectType.getDescribe().fields.getMap();
SObjectField sObjectField = fieldMap.get(fieldName);
return getPicklistEntryMap(sObjectType, sObjectField);
}
/**
* Retrieves a Map of PicklistEntry values for a given SObjectType and SObjectField.
* @param sObjectType The SObjectType of the object.
* @param sObjectField The SObjectField representing the field.
* @return Map A map containing picklist values with their labels as keys.
*/
public static Map getPicklistEntryMap(SObjectType sObjectType, SObjectField sObjectField) {
Map picklistEntryMap = new Map();
Map fieldMap = sObjectType.getDescribe().fields.getMap();
DescribeFieldResult fieldResult = fieldMap.get(sObjectField).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:
Instantiate the Class
FSRK_PicklistValueFetcher picklistFetcher = new FSRK_PicklistValueFetcher();
Invoke the Method
String objectName = 'Account';
String fieldName = 'Type';
Map picklistValues = picklistFetcher.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.