Filter Picklist values by Record Type in Apex

A typical issue for Lightning developers is the impossibility to filter picklist values available for a specific record.

Think at you while exposing a Lightning component that collects some Case information. The user populates all inputs, but can select more picklist values than it should since you have no way to filter them out based on the Record Type.

Using the Get Picklist Values included in the User Interface API you can easily detect which values are available for a specific SObjectType, RecordTypeId and Picklist field.

Use this Apex method to find the values currently enabled picklist values:

public static Map<String, String> getValues(String objectType, String recordTypeId, String fieldName) {
    //Endpoint
    String endpoint = URL.getSalesforceBaseUrl().toExternalForm();
    endpoint += '/services/data/v41.0';
    endpoint += '/ui-api/object-info/{0}/picklist-values/{1}/{2}';
    endpoint = String.format(endpoint, new String[]{ objectType, recordTypeId, fieldName });
    EncodingUtil.urlEncode(endpoint,'UTF-8');
    
    //HTTP Request send
    HttpRequest req = new HttpRequest();
    req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId()); 
    req.setEndpoint(endpoint);
    req.setMethod('GET');
    Http http = new Http();
    HTTPResponse res = http.send(req);
    
    //Parse response
    Map<String,String> result = new Map<String,String>();
    Map<String,Object> root = (Map<String,Object>) JSON.deserializeUntyped(res.getBody());
    if(!root.containsKey('values')){ 
        return result; 
    }
    List<Object> pValues = (List<Object>)root.get('values');
    for(Object pValue : pValues){
        Map<String,Object> pValueMap = (Map<String,Object>)pValue;
        result.put((String)pValueMap.get('value'), (String)pValueMap.get('label'));
        System.debug(result);
    }
    
    return result;
}

 

Just remember to enable the instance URL, or you won’t be able to make the REST API calls:

Christian Tinghino

Senior Developer, 2x Salesforce certified

2 thoughts to “Filter Picklist values by Record Type in Apex”

Leave a Reply

Your email address will not be published. Required fields are marked *