Filter Picklist values by Record Type in Apex

A typical issue 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:

 

[EDIT]

If you’re experiencing authorization problems in lightning components context-aware, you can solve creating a Connected App, an Auth provider and a Named Credential.

This is a bit tricky instead of the simple-session-id-way, but it works. Read here for more details: https://rajvakati.com/2018/01/28/salesforce-ui-api-lightning-examples/

Also, I made this sample video to prove that it works (note the Account > SLA picklist values being filtered according to the Record Type setting):

 

Christian Tinghino

Senior Developer, 2x Salesforce certified

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

  1. Its throwing below error :
    [{“message”:”This session is not valid for use with the REST API”,”errorCode”:”INVALID_SESSION_ID”}]

    Can you please help me on the same as I am new in rest api call.

  2. This doesn’t work for me, and I’m receiving the following error: This session is not valid for use with the REST API. Has anyone else experienced this?

    1. It is working fine with in Developer Console. however it gives below error for the Community User.

      System.HttpResponse[Status=Forbidden, StatusCode=403]
      10:14:54.0 (135468447)|USER_DEBUG|[22]|DEBUG|System.HttpResponse[Status=Forbidden, StatusCode=403]

  3. Hi CHRISTIAN,

    I am also in the same boat. IT is working fine when we run the code Developer Console as anonymous script. When when we run on apex we are ending up with an error.

    Error Message: INVALID_SESSION_ID, message=This session is not valid for use with the REST API}

    Could you please suggest on this.

    Thanks in advance.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.