Filter Picklist Values Based on Record Type in Lightning

    sfdcsharepoint.com

    Filter Picklist Values Based on Record Type

      n

    1. Retrieving a picklist value based on record type is possible in VF page using standard controller
    2. n

    3. In lightning, Salesforce UI API supports a functionality to filter a picklist value based on record type based on this idea
    4. n

    5. You can download the code from Here
    6. n

    n

    Use Case: 

    n

    I have picklist values based on Record Type defined as below:

    n

    Now, If we want to get this metadata in lightning and want to display dropdowns based on Record Type of any given record.

    n

    We might be thinking of using any Schema class. But unfortunately, we don’t have schema class supported for this use case.  We wanted output like this for the record which has record type mentioned in the previous screenshot.

    n

    So, Let’s take a look at the solution.

    n

    Below is the approach to leverage Salesforce UI API to retrieve picklist value based on record type:

      n

    1. Create a connected app
    2. n

    3. Create an Auth Provider
    4. n

    5. Create Named Credentials
    6. n

    7. Create lightning component
    8. n

    9. Create Apex class to call UI API
    10. n

      n

    1. Create a connected app:
    2. n

    3. setup > create apps > create new app
    4. n

    5. Provide any URL as a callback URL for now. We will replace it with new URL in later steps when we will create Auth Provider
    6. n

    7. For Oauth scope provide “Full access (full)” & ”Perform requests on your behalf at any time (refresh_token, offline_access)”
    8. n

    connected_app

      n

    1. Create an Auth Provider
    2. n

    3. Create Auth Provider from Setup > Security Control > create a new Auth. provider
    4. n

    5. Set provider type as “Salesforce”
    6. n

    7. Provide consumer key & consumer secret from apps that is created in step 1
    8. n

    9. Set the default scope as a “full refresh_token offline_access”
    10. n

    11. Click save
    12. n

    auth_provider
      n

    1. Cope the Callback URL from “Salesforce Configuration” section and paste it to Callback URL in app that you have created in step 1.
    2. n

      n

    1. Create Named Credentials
    2. n

    3. Setup > Named Credentials > Create new named credentials
    4. n

    5. Set the URL as a base URL of your org
    6. n

    7. Set Identity type as a “Named Principal”
    8. n

    9. Set authentication protocol as a “Oauth 2.0”
    10. n

    11. Select Authentication Provider as a Auth. Provider that you created in step 2.
    12. n

    13. Provide the scope as a “full refresh_token offline_access”
    14. n

    15. Select “Start Authentication Flow on Save”
    16. n

    17. Click Save > It will ask for credentials to authenticate, provide that
    18. n

    named_credentials

      n

    1. Create a lightning component
    2. n

    n   n   n   n   n   n   n   n   n   n   n   n   n   n   n   n   n   	n           n       n   n   n
      n

    1. Javascript controller.js code
    2. n

    ({n    doInit : function(component, event, helper) {n        helper.getPicklistValuesBasednRecordType(component);n    },n})
      n

    1. Javascript helper.js code
    2. n

    ({n    getPicklistValuesBasednRecordType : function(component) {n        n        var objectAPIName = component.get("v.objectAPIName");n        var fieldAPIName = component.get("v.fieldAPIName");n        var recordTypeDeveloperName = component.get("v.recordTypeDeveloperName");n        n        var action = component.get("c.getPicklistValueBasedonRecordType");n        n        action.setParams({n            objectAPIName : objectAPIName,n            fieldAPIName : fieldAPIName,n            recordTypeDeveloperName : recordTypeDeveloperNamen        });n        n        action.setCallback(this, function(response){n            this.handleResponse(response, component);n        });n        n        $A.enqueueAction(action);n        n	},n    n    handleResponse : function(response, component){n        if (response.getState() === "SUCCESS") {n            if (!$A.util.isEmpty(response.getReturnValue())) {n                var picklistOptions = [];n                var noneValue = {};n                noneValue["value"] = "";n                noneValue["label"] = "--None--";n                picklistOptions.push(noneValue);n                var returnedValues = JSON.parse(response.getReturnValue());n                if (!$A.util.isEmpty(returnedValues)) {n                    returnedValues.forEach(function(returnedValue){n                        var picklistValue = {};n                        picklistValue["value"] = returnedValue.value;n                        picklistValue["label"] = returnedValue.label;n                        picklistOptions.push(picklistValue);n                    });n                    component.set("v.pickListOptions", picklistOptions);n                }n            }else{n                console.log("Couldn't find an picklist values.");n            }n        } else if (response.getState() === "ERROR") {n            var errors = res.getError();n            if (errors) {n                if (errors[0] && errors[0].message) {n                    console.log(errors[0].message);n                }n            }n        } else{n            console.log("Unknow error!");n        }n    },n})

      n

    1. Create an apex controller
    2. n

    /**n* @Author		:		Rajat Koradiyan* @Date		:		20-Sept-2018n* @Desc		:		Controller for picklist based on record type lightning componentn* */npublic with sharing class PicklistBasedOnRecordTypeController {n   n   @AuraEnabled n   public static String getPicklistValueBasedonRecordType(String objectAPIName, String fieldAPIName, String recordTypeDeveloperName){n       n       list picklistValues = new list();n       n       //get record type Idn       list recordTypes = [Select Id, Name From RecordType  Where SobjectType = :objectAPIName and DeveloperName = :recordTypeDeveloperName limit 1];n       Id recordTypeId = (!recordTypes.isEmpty()) ? recordTypes.get(0).Id : null;n       n       if(recordTypeId != null){n           n           String method = 'GET';n           String endpoint = String.format('/services/data/v43.0/ui-api/object-info/{0}/picklist-values/{1}/{2}', new String[]{ objectAPIName, recordTypeId, fieldAPIName });n           n           HttpRequest request = new HttpRequest();n           request.setEndpoint('callout:UI_API_Named_Credentials'+endPoint);n           request.setMethod(method);n           n           HTTPResponse response = (new Http()).send(request);n           n           if(response.getStatusCode() == 200){n               n               Map root = (Map) JSON.deserializeUntyped(response.getBody());n               if(root.containsKey('values')){ n                   List picklistVals = (List)root.get('values');n                   for(Object picklistVal : picklistVals){n                       Map picklistValMap = (Map) picklistVal;n                       picklistValue pickVal = new picklistValue();n                       pickVal.value = (String) picklistValMap.get('value');n                       pickVal.label = (String) picklistValMap.get('label');n                       picklistValues.add(pickVal);n                   }n               }n               n           }n           n       }n       n       return JSON.serialize(picklistValues);n   }n   n   public class PicklistValue{n       public String value {get;set;}n       public String label {get;set;}n   }n}
    

    n

    #Lightning #UIAPI

    Leave a Reply

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