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:
- Initiate the selectOption list
- Get the schema of the object
- Describe the properties of the object
- Get the field map in a Map with API name of the field as key
- iterate over the map value for the picklist field
- 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