Using Dynamic Apex to retrieve Picklist Values

With the increasing popularity and adoption of the platform, I am seeing a huge growth in custom Visualforce pages, in particular pages which require interaction with multiple objects. One requirement that comes up regularly is how to display picklist values from an object when the page is using a custom controller. 

In order to achieve this, we have to look at the very powerful and useful Dynamic Apex Describe Information capabilities.  These capabilities allow us to interrogate a field or sObject, and describe their characteristics. In our requirement above, we want to describe the fields on an object, in particular, a picklist field to determine its list of values.

Lets say we have a custom object called OfficeLocation__c. OfficeLocation__c contains a number of fields, one of which is a picklist of country values called, creatively enough, Country__c. Our customer requirements are to include the picklist of countries on a Visualforce page which uses a custom controller. The first thing we need to do, within our controller is use the getDescribe() method to obtain information on the Country__c field:

Schema.DescribeFieldResult fieldResult = OfficeLocation__c.Country__c.getDescribe();

We know that Country__c is a picklist, so we want to retrieve the picklist values:

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

The only thing left for us to do is map the picklist values into an <apex:selectOptions> tag can use for display. Here is the entire method from our controller to do this:

public List<SelectOption> getCountries()
  List<SelectOption> options = new List<SelectOption>();
   Schema.DescribeFieldResult fieldResult =
   List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
   for( Schema.PicklistEntry f : ple)
      options.add(new SelectOption(f.getLabel(), f.getValue()));
   return options;

With our controller logic all complete, we can call the getCountries() method from our Visualforce page,  and populate the <apex:selectList> tag:

<apex:selectList id="countries" value="{!Office_Location__c.Country__c}"
         size="1" required="true">
  <apex:selectOptions value="{!countries}"/>

December 9, 2008

Leave your comments...

Using Dynamic Apex to retrieve Picklist Values