2

Is it possible to automate the process of picklist values retrieval from the backend?

Here is how I am doing it right now:

@AuraEnabled
public static List<String> retrieveMyObjectMyFieldOptions() {
    List<String> res = new List<String>();

    Schema.DescribeFieldResult fieldResult
            = MyObject__c.MyField__c.getDescribe();
    List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
    for(Schema.PicklistEntry f: ple) {
        res.add(f.getLabel());
        res.add(f.getValue());
    }

    return res;
}

Is it possible to pass two strings to a method and get the same list as above? In other words is it possible to change the signature to the following:

public static retrieveMyObjectMyFieldOptions(String MyObject, String MyField)?

5

I've already written an answer about this, but the question doesn't make sense to call it a duplicate, so I'll repost that code here.


// Wrapper class to provide label/value.
public class PicklistValue {
    @AuraEnabled public string label, value;
    PicklistValue(String lab, String val) {
        label = lab;
        value = val;
    }
}
// Top-level wrapper to make it look nice when the client gets the results.
public class Response {
    @AuraEnabled public PicklistValue[] values = new PicklistValue[0];
}
@AuraEnabled
public static Response getPicklistData(String objectName, String fieldName) {
    Response res = new Response();
    // 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 value: ((SObject)(Type.forName('Schema.'+objectName).newInstance())).getSObjectType()
        .getDescribe().fields.getMap().get(fieldName).getDescribe().getPicklistValues()) {
            res.values.add(new PicklistValue(value.getValue(), value.getLabel()));
        }
    return res;
}

NOTE: We need to return the value and the label, because they might not be the same thing. If you don't do it this way, expect problems in your Apex code when you try to save the label-version of the picklist entry rather than the api-value-version of the entry.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.