Play Games

Search This Blog

Wednesday, December 18, 2013

How to access picklist values in Apex?

Sometimes we may have a requirement to get all the values of a picklist field in apex.
For example in account object ,active__c is a picklist field with values low,medium and high.
In this type of scenarios ,we need to use dynamic apex.

Dynamic apex allow us to interrogate a field or sObject, and  describe their characteristics.

The first thing we need to do, within our controller is use the getDescribe() method to obtain information on the  active__c  field:

Schema.DescribeFieldResult fieldResult = account.active__c.getDescribe();
We know that active__c is a picklist, so we want to retrieve the picklist 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());//add the value  to our list
   }
thats it,the lstPickvals  contains all the picklist field values 
i.e here low,medium,high.
 

3 comments:

  1. Great post..short and simple...:)

    ReplyDelete
  2. when i was looking for this, i didnt get exact things. this one is easy to use and awesome.:)

    ReplyDelete