how to get a picklist all values in apex controller
This is very common requirement and we have few good blogs from where you can directly get the code
- Salesforce Developers Blog: Using Dynamic Apex to retrieve Picklist Values
Example code:
public static List<String> getPicklistValues(String ObjectApi_name,String Field_name){
List<String> lstPickvals=new List<String>();
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(ObjectApi_name);//From the Object Api name retrieving the SObject
Sobject Object_name = targetType.newSObject();
Schema.sObjectType sobject_type = Object_name.getSObjectType(); //grab the sobject that was passed
Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); //describe the sobject
Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); //get a map of fields for the passed sobject
List<Schema.PicklistEntry> pick_list_values = field_map.get(Field_name).getDescribe().getPickListValues(); //grab the list of picklist values for the passed field on the sobject
for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
lstPickvals.add(a.getValue());//add the value to our final list
}
return lstPickvals;
Here is the Utility Method i use to get all the picklist values for an object and Field.
In your case you need select option for the allow user to select if you use in visualforce page
global static list<SelectOption> getPicklistValues(SObject obj, String fld){
list<SelectOption> options = new list<SelectOption>();
// Get the object type of the SObject.
Schema.sObjectType objType = obj.getSObjectType();
// Describe the SObject using its object type.
Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
// Get a map of fields for the SObject
map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
// Get the list of picklist values for this field.
list<Schema.PicklistEntry> values =
fieldMap.get(fld).getDescribe().getPickListValues();
// Add these values to the selectoption list.
for (Schema.PicklistEntry a : values)
{
options.add(new SelectOption(a.getLabel(), a.getValue()));
}
return options;
}
}
I think this may work. I ran some tests on a standard field and was able to see the values through the console.
Schema.DescribeFieldResult studentStatus = Student__c.Student_Status__c.getDescribe();
List<Schema.PicklistEntry> studentStatusValues = studentStatus.getPicklistValues();