You have the ability to craft a dynamic method for fetching picklist labels and values for any object and field in Salesforce. Below is a dynamic method that accepts the object API name and field API name as parameters:
public class PicklistUtils {
public static List<Map<String, String>> getPicklistValues(String objectApiName, String fieldApiName) {
List<Map<String, String>> picklistData = new List<Map<String, String>>();
try {
// Describe the object and field
Schema.DescribeSObjectResult objectDescribe = Schema.getGlobalDescribe().get(objectApiName).getDescribe();
Schema.DescribeFieldResult fieldDescribe = objectDescribe.fields.getMap().get(fieldApiName).getDescribe();
// Check if the field is a picklist
if (fieldDescribe.getType() == Schema.DisplayType.Picklist) {
// Get the picklist values and labels
List<Schema.PicklistEntry> picklistValues = fieldDescribe.getPicklistValues();
// Iterate through the picklist values and labels
for (Schema.PicklistEntry picklistEntry : picklistValues) {
Map<String, String> picklistItem = new Map<String, String>();
picklistItem.put('label', picklistEntry.getLabel());
picklistItem.put('value', picklistEntry.getValue());
picklistData.add(picklistItem);
}
}
} catch (Exception e) {
// Handle exceptions as needed
}
return picklistData;
}
}
Now, you can invoke the method to obtain the value. For example:
String objectApiName = 'MyObject__c';
String fieldApiName = 'MyPicklist__c';
List<Map<String, String>> picklistValues = PicklistUtils.getPicklistValues(objectApiName, fieldApiName);
for (Map<String, String> picklistItem : picklistValues) {
String label = picklistItem.get('label');
String value = picklistItem.get('value');
// Use label and value as needed
System.debug('Label: ' + label + ', Value: ' + value);
}
Enjoy your learning journey!
