Saturday 1 December 2012

Add values of a object Picklist to selectOption variable


Suppose we need to add values of a picklist which is defined in the object, to a variable of
type selectoption in the controller. The code for that is below:

Steps:

  1. Initiate the selectOption list
  2. Get the schema of the object
  3. Describe the properties of the object
  4. Get the field map in a Map with API name of the field as key
  5. iterate over the map value for the picklist field 
  6. add values to the selectOption list.



Controller:

public List<selectOption> getPicklistValues(){  
                // define a selectoption variable
        List<selectOption> pickListValues= new List<selectOption>();
   
         //retrieves the schema of the object
        Schema.sObjectType sobject_type = test_Object__c.getSObjectType();

        Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe();

        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap();
       
         // picklist_field__c is the API name of the picklist field defined in the object
         List<Schema.PicklistEntry> pick_list_values =                       field_map.get('picklist_field__c').getDescribe().getPickListValues();    
     
for (Schema.PicklistEntry a : pick_list_values){
pickListValues.add(new selectOption(a.getLabel(), a.getValue()));
}
         return pickListValues;
}

No comments:

Post a Comment