Today I came across a requirement where I need to get all the picklist values for a field and to show them on a visualforce. Thogh it is not a very complex requirement and I have implemented it couple of times before as well, I spent some time on it because I implemented it this time also.
I could have saved my time if I had a reusable code for this. Thus I finally decided to develope a reusable method for the same and to post it here on the blog so that the other techies :) can use it without wasting their time as I did.
Below is the method i wrote:
// method to get the available picklist values for the Sobject Field
public static List<selectoption> getPicklistValues(String objectName, String picklistField, Boolean addNoneVal) {
List<selectoption> options = new List<selectoption>();
// Add none value if defined in parameter
if(addNoneVal) {
options.add(new SelectOption('', '--None--'));
}
// add the picklist values to the list of select options
for(Schema.PicklistEntry ple: Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap().get(picklistField).getDescribe().getPicklistValues()) {
options.add(new SelectOption(ple.getValue(), ple.getLabel()));
}
// return the prepared list.
return options;
}
You just need to add this in your apex class and call it like below:
Now you can use this getter method in your visaulforce page which will look like below when executed:
public List<selectoption> getAccountTypePicklistValues() {
return getPicklistValues('Account', 'Type', true);
}
Now you can use this getter method in your visaulforce page which will look like below when executed:

P.S. : I have used the "Type" field from "Account" object for the example. You can change it per your requirements.
Very Useful. Thanks
ReplyDelete