Access picklist values in Apex.

Have you ever worked on the requirement to get all the values of picklist field in apex?
If no, you may have to work on it in near future.


For example in account object , grade__c is a picklist field with values average, good, excellent.

So for implementing such condtion we are going to use dynamic apex.

What Dynamic apex does here is that it allows to query a field or sObject, and  describe it's attributes.

1) First step is to create a controller with  getDescribe() method which will enable us to obtain information on the  grade__c  field

Schema.DescribeFieldResult fieldResult = account.grade__c.getDescribe();

As grade__c is a picklist field of which we need to retrieve all values:

List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();

If we want to get picklist values in list do the following:
List<String> lstPickvals=new List<String>();
 for (Schema.PicklistEntry a : ple ) 
   {
      lstPickvals.add(a.getValue());
   }

Now we have all the values of picklist grade__C i.e. average, goood and excellent in lstPickvals. :)

Comments

Popular posts from this blog

List of Key Prefixes in Salesforce

SFDX Install CPQ in Scratch org