How to get picklist values for fields in apex salesforce

H

//get all picklist option values using the type of sobject and specific picklist field
//TODO: move this into platform wide sobject utils class as it is not domain specific
public static List<String> getPickListValues(String objectName, String fieldName)
{
try
{
List<String> pickListValuesList = new List<String>();
sObject sObj = Schema.getGlobalDescribe().get(objectName).newSObject();
Schema.sObjectType sObjType = sObj.getSObjectType();
Schema.DescribeSObjectResult sObjDescribe = sObjType.getDescribe();
Map<String, Schema.SObjectField> sObjFieldMap = sObjDescribe.fields.getMap();
List<Schema.PicklistEntry> sObjPickListEntryList = sObjFieldMap.get(fieldName).getDescribe().getPickListValues();
System.debug(‘>>>>>>>>>>>>>>>>>>>> sObjPickListEntryList for ‘ + objectName + ‘:’ + fieldName + ‘ = ‘ + sObjPickListEntryList);
for(Schema.PicklistEntry sObjPickListEntry : sObjPickListEntryList)
{
pickListValuesList.add(sObjPickListEntry.getLabel());
}
return pickListValuesList;
}
catch(exception e)
{
ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,
‘Unable to find setup information for the field ‘ + objectName + ‘.’ + fieldName +
‘. Please contact your system administrator.’);
ApexPages.addMessage(msg);
System.Debug(‘>>>>>>>>>>>>>>>>>>>> Exception in IPA_Utils.class:’ + msg + ‘(‘ + e.getMessage() + ‘)’);
return null;
}
}

About the author

kalpesh.surana
By kalpesh.surana

Category