1

I wrote a generic method that takes an object, field and value as string parameters and returns the picklist label.

I was wondering if there is a more efficient way to write the method instead of returning all fields in a map from the sObject and then looping over to find the specific field?

Here is the method:

    public static String getSobjectPicklistLabel(string obj, string fld, string value) {
        String retval = '';
        Map<String , Schema.SObjectType> globalDescription = Schema.getGlobalDescribe();
        Schema.sObjectType sObjType = globalDescription.get(obj);
        Schema.DescribeSObjectResult sObjectResult = sObjType.getDescribe();
        Map<String , Schema.SObjectField> mapFieldList = sObjectResult.fields.getMap();
        for(Schema.SObjectField field : mapFieldList.values()) {
            Schema.DescribeFieldResult fieldResult = field.getDescribe();
            if(fieldResult.getLabel() == fld) {
                List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
                for(Schema.PicklistEntry f : ple) {
                    if(f.getValue() == value) {
                        retval = f.getLabel();
                        break;
                    }                               
                }
            }
        }
        return retval;
    }
1
  • While my answer is the most literal interpretation of your request, it should be noted that if you're doing this in order to get the label of a value that you're querying, you can use toLabel.
    – sfdcfox
    Commented Sep 4, 2018 at 21:05

1 Answer 1

2

Yes, you can use the code I devised as a starting point:

public static String getLabelForPicklistValue(String objectName, String fieldName, String value) {
    // Dynamically create a reference to an object and field, and describe.
    // NOTE: No error checking, so if it's not a picklist, expect a crash.
    for(PicklistEntry entry: ((SObject)(Type.forName('Schema.'+objectName).newInstance())).getSObjectType()
        .getDescribe().fields.getMap().get(fieldName).getDescribe().getPicklistValues()) {
        if(entry.getValue() == value) {
            return entry.getLabel();
        }
    }
    return null; // value not found...
}
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .