Get Picklist Values in Apex Salesforce

This post will explain how to Get Picklist Values in Apex Salesforce. This implementation will have two ways to fetch picklist values in Apex. One with hardcoded for a particular Object and Field and another one is dynamically that will work for any Object and Field. Let’s get into the implementation.

Implementation

As part of this demonstration, I have created a custom field Subjects__c on the Account object.

If we already know the name of the Object and Field, we can directly make a call to getDescribe() method to get the Schema.DescribeFieldResult. Then, we just need to call getPickListValues() to get the Label and Values in Apex.

Check out the code for the same below:

Schema.DescribeFieldResult objFieldDescribe = Account.Subjects__c.getDescribe();
List<Schema.PicklistEntry> lstPickListValues = objFieldDescribe.getPickListValues();
for (Schema.PicklistEntry objPickList : lstPickListValues) {
    System.debug('Value = ' +objPickList.getValue() +' , Label = ' +objPickList.getLabel());
}

This is how our debugs look after printing Value and Label of picklist values.

Get Picklist Values in Apex Salesforce
Get Picklist Values in Apex Salesforce

Also Read:

Get Picklist Values in Apex Dynamically

To fetch the picklist values in Apex dynamically, we need to make an extra call to getGlobalDescribe() to get the Schema.SObjectType of that particular object. Then, we can use it to fetch the DescribeSobjectResult.

Once we get the DescribeSobjectResult, we need to call fields.getMap() to get the Map of Schema.SObjectField which can be used to fetch the Value and Label for picklist values.

This is how the code looks:

String strObjectName = 'Account';
String strPicklistField = 'Subjects__c';
Map<String, String> mapPickListValues = new Map<String, String>();
Schema.SObjectType objSobjectType = Schema.getGlobalDescribe().get(strObjectName);
Schema.DescribeSObjectResult objDescribeSobject = objSobjectType.getDescribe();
Map<String, Schema.SObjectField> mapFields = objDescribeSobject.fields.getMap();
List<Schema.PicklistEntry> lstPickListValues = mapFields.get(strPicklistField).getDescribe().getPickListValues();
for (Schema.PicklistEntry objPickList : lstPickListValues) {
    System.debug('Value = ' +objPickList.getValue() +' , Label = ' +objPickList.getLabel());
}

Also Read:

It will generate the same output as the first example. You just need to assign the object name to strObjectName and picklist field name to strPicklistField, and it will get the picklist values in Apex dynamically.

Please Subscribe here if you don’t want to miss new implementations.

To know more about DescribeSObjectResult, check official Salesforce documentation here.

See you in the next implementation, thank you!

Leave a Comment