Skip to main content

Generic Class to get Dependency of Dependent Pick-list In Apex

Dependent Picklist values Dependency

Dependent Picklist values do not have any dependency when retrieved via Apex Code.

This Following Class will returned a map which has Key as Controlling Values and Values are the list of dependent values(In LowerCase).
Map Key =  Controlling Values,
Map Values = list of dependent values.

Class:-
/***********************--START--********************************/
/**
* @File Name          : DependencyForPicklistApex.cls
* @Description        : CR-DR
* @Author             : Devraj Tomar
* @Group              : DR Groups
* @Last Modified By   : Devraj Tomar
* @Modification Log   : 
**/
public class DependencyForPicklistApex {
    
    public static Map<String, Set<String>> getFieldDependencies(String objectName, String controllingField, String dependentField){
        Map<String, Set<String>> controllingInfo = new Map<String, Set<String>>();
        Schema.SObjectType objType = Schema.getGlobalDescribe().get(objectName);
        Schema.DescribeSObjectResult describeResult = objType.getDescribe();
        Schema.DescribeFieldResult controllingFieldInfo = describeResult.fields.getMap().get(controllingField).getDescribe();
        Schema.DescribeFieldResult dependentFieldInfo = describeResult.fields.getMap().get(dependentField).getDescribe();
        List<Schema.PicklistEntry> controllingValues = controllingFieldInfo.getPicklistValues();
        List<Schema.PicklistEntry> dependentValues = dependentFieldInfo.getPicklistValues();
        for(Schema.PicklistEntry currControllingValue : controllingValues){
            controllingInfo.put(currControllingValue.getValue(), new Set<String>());
        }
        for(Schema.PicklistEntry currDependentValue : dependentValues){
            String jsonString = JSON.serialize(currDependentValue);
            MyPickListInfo info = (MyPickListInfo) JSON.deserialize(jsonString, MyPickListInfo.class);
            String hexString = EncodingUtil.convertToHex(EncodingUtil.base64Decode(info.validFor)).toUpperCase();
            Integer baseCount = 0;
//toLowerCase can be changed to uppercase and getLabel() can be changed to getValue() based on requirement.
            for(Integer curr : hexString.getChars()){
                Integer val = (curr >= 65)?(curr - 65 + 10):(curr - 48);
                    if((val & 8) == 8){controllingInfo.get(controllingValues[baseCount + 0].getValue()).add(currDependentValue.getLabel().toLowerCase());}/
                if((val & 4) == 4){controllingInfo.get(controllingValues[baseCount + 1].getValue()).add(currDependentValue.getLabel().toLowerCase());}
                if((val & 2) == 2){controllingInfo.get(controllingValues[baseCount + 2].getValue()).add(currDependentValue.getLabel().toLowerCase());}
                if((val & 1) == 1){controllingInfo.get(controllingValues[baseCount + 3].getValue()).add(currDependentValue.getLabel().toLowerCase());}
                baseCount += 4;
            }            
        } 
        return controllingInfo;
    }
    
    public class MyPickListInfo{
        public String validFor;
    }
}

/***********************--END--********************************/

How to Use:
Syntax :
Map<String, Set<String>> STATES_BY_COUNTRYCODE= DependencyForPicklistApex.getFieldDependencies('ObjectName', 'ControllingFieldAPIName','DependentFieldAPIName');

Example : 
static final Map<String, Set<String>> STATES_BY_COUNTRYCODE= DependencyForPicklistApex.getFieldDependencies('Account', 'BillingCountryCode','BillingStateCode');


Note : In Account Object BillingCountry is the Controlling Field for BillingState.

With the little modification this code can work for BillingCountry instead of  BillingCountryCode.

Any Issue Feel free to Comment Below :-

Comments

  1. Hi,
    1. how do we find the controlling value based on the dependent picklist?
    2. What is the meaning of this hardcoded number base 64, 48 etc?

    Could you please create a document with all the information
    Thanks!

    ReplyDelete

Post a Comment

Popular posts from this blog

Maintain Your Platform Developer I Certification for Winter ’25

  Make Invocable Actions Easier to Configure with New InvocableVariable Modifiers Simplify the configuration of invocable actions using new modifiers from Salesforce. Both the defaultValue and placeholderText modifiers will appear in Flow Builder for the Action elements that correspond to an invocable method. Here’s how to use them. defaultValue Modifier : Set a default value for an input parameter. When the action is used, the input parameter will have a predefined value unless changed by the user. placeholderText Modifier : Set custom placeholder text for an input parameter. Text can provide examples or additional guidance to help users understand what to enter in the input field. Accessing these modifiers in Flow Builder makes it easier to configure and use the actions within your flows. This change applies to Lightning Experience and Salesforce Classic in Performance, Unlimited, Developer, Enterprise, and Database.com editions.

Maintain Your Administrator Certification for Spring ’24

Maintain Your Administrator Certification for Spring ’24 Intelligence Views Intelligence views are now available for leads, contacts, and accounts in Sales Cloud. Turn on a view in Setup and then add the Intelligence View button to the view-button layout for the applicable page. New Salesforce organizations include the views by default, but admins for existing orgs can enable: Lead Intelligence View Contact Intelligence View Account Intelligence View Find specifics about these views in the next three topics. Turn on Contact Intelligence View in Contact Intelligence View Setup and add the Intelligence View button to the Contact List View button layout. To view engagement metrics, enable Email Tracking in the Inbox section of Sales Engagement Setup. To see the Intelligence View, users go to the Contact home page and click Intelligence View. To view engagement metrics, choose Engagement Metrics from the Metrics menu. To see the Account Intelligence view, go to the account home page and cl...

Maintain Your Administrator Certification for Spring ’25

  Manage Included Permission Sets in Permission Set Groups via Summaries Update user access more efficiently by specifying which permission set groups include a permission set directly from the permission set’s summary. Previously, to manage included permission sets, you were required to navigate to each permission set group’s page. From Setup, in the Quick Find box, enter  Permission Sets , and select Permission Sets. Select a permission set, and then click  View Summary . In the Related Permission Set Groups tab, click  Add  or  Remove . This change applies to Lightning Experience and Salesforce Classic (not available in all orgs) in Contact Manager, Group, Essentials, Professional, Enterprise, Performance, Unlimited, Developer, and Database.com editions. Sort List Views by Multiple Columns To see your data in a more intuitive way and make your list views more actionable, you can now sort list views on object home pages by up to five columns. Select the c...

Translate