Get Picklist Values in Apex

In Interview question part 4, we discussed how dynamic Apex can be used to retrieve metadata information about Objects or fields on Object.

While writing highly configurable code, there are situation where we want to avoid hardcoding picklist values and read it realtime from field.

Below code snippet takes two parameter, Object and picklist field name. On basis of these two inputs, we can read either Picklist label or Picklist value (API Name)

String objectName = 'Contact';
String fieldName ='LeadSource';
  
Schema.SObjectType s = Schema.getGlobalDescribe().get(objectName) ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap() ;
Schema.DescribeFieldResult fieldResult = fields.get(fieldName).getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
for( Schema.PicklistEntry pickListVal : ple){
    System.debug(pickListVal.getLabel() +' '+pickListVal.getValue());
}    

Posted

in

by


Related Posts

Comments

3 responses to “Get Picklist Values in Apex”

  1. Maneesh Avatar
    Maneesh

    Hi!How to test this?

    1. MadCat Avatar
      MadCat

      System.debug() – logged values

  2. donalddedman1cd0f78777 Avatar
    donalddedman1cd0f78777

    Hi, long time reader, first time response.
    I’ve used this solution to get the picklist values (ple’s) but I’ve run into 2 different Use Cases where in one:
    1st Use Case: I want to be able to handle existing Invalid ple’s in our database, however, it seems that SF has placed a restriction to prevent this? Any thoughts or workarounds?

    2nd Use Case: I want to assign an order for say a Case Status field, kinda like processing steps, which will be dependent on other object picklist status’s as well, but I’m trying to keep my code both clean and scalable without using a bunch of conditional switch statements with hard coded picklist values. Any thoughts would be helpful?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading