Quantcast
Channel: Salesforce Online Training
Viewing all articles
Browse latest Browse all 84

How to Get Dependent Picklist Options in Apex?

$
0
0

Question

How to Retrieve Dependent Picklist Values in Apex?

I am working with a pair of dependent picklists and need to determine the valid options in the dependent field for each value in the controlling field using Apex.

Here’s an example setup:

  • Controlling_Field__c:
    Fruit, Vegetable, Dairy
  • Dependent_Field__c:
    • Fruit: Apple, Banana, Pear
    • Vegetable: Tomato, Eggplant, Lettuce
    • Dairy: Milk, Cheese, Yogurt

I’ve attempted to use getPicklistValues(), but it doesn’t provide dependency information. Ideally, I’m looking for functionality akin to this pseudocode:

controllingOptions = dependentfield.getPicklistValues();
for (option : controllingOptions) {
    dependentOptions = dependentfield.getPicklistValuesFor(option);
    do_something_with_it();
}

My Questions:

  1. How can I retrieve the dependency mapping between controlling and dependent picklist values in Apex?
  2. Is there a standard way to get the dependent options programmatically for each controlling field value?

Keywords: Salesforce, Apex, Dependent Picklists, Picklist Values, Dependency Mapping

Answer

In Salesforce, when working with dependent picklists, it can be challenging to retrieve the valid options for the dependent field based on the selected value in the controlling field. While the getPicklistValues() method in Apex allows you to fetch picklist values, it doesn’t directly provide the dependency information. However, Salesforce includes dependency information in the metadata, and this can be accessed using the validFor property of picklist entries.

Here’s how you can achieve this in Apex:

First, use the DescribeFieldResult of the dependent field to fetch picklist values. Each dependent picklist value contains a validFor property, which is a Base64-encoded string. This string can be decoded into bits, where each bit represents whether the dependent value is valid for a specific controlling field value.

The following example demonstrates how you can determine the valid dependent options for each controlling field value:

public class DependentPicklistHelper {
    public static Map<String, List<String>> getDependentOptions(String objectName, String controllingField, String dependentField) {
        Map<String, List<String>> dependentOptions = new Map<String, List<String>>();

        // Get field describe for the controlling and dependent fields
        Schema.SObjectType objectType = Schema.getGlobalDescribe().get(objectName);
        Schema.DescribeSObjectResult describeObject = objectType.getDescribe();
        Map<String, Schema.SObjectField> fields = describeObject.fields.getMap();
        Schema.DescribeFieldResult controllingFieldDescribe = fields.get(controllingField).getDescribe();
        Schema.DescribeFieldResult dependentFieldDescribe = fields.get(dependentField).getDescribe();

        // Retrieve controlling field values
        List<Schema.PicklistEntry> controllingValues = controllingFieldDescribe.getPicklistValues();
        List<Schema.PicklistEntry> dependentValues = dependentFieldDescribe.getPicklistValues();

        // Decode dependencies
        for (Schema.PicklistEntry controllingValue : controllingValues) {
            String controllingValueLabel = controllingValue.getLabel();
            List<String> validDependentValues = new List<String>();

            for (Schema.PicklistEntry dependentValue : dependentValues) {
                String validFor = dependentValue.getValidFor();
                if (isDependentOptionValid(validFor, controllingValues.indexOf(controllingValue))) {
                    validDependentValues.add(dependentValue.getLabel());
                }
            }

            dependentOptions.put(controllingValueLabel, validDependentValues);
        }
        return dependentOptions;
    }

    // Helper method to check if a dependent option is valid
    private static Boolean isDependentOptionValid(String validFor, Integer index) {
        Blob decodedBlob = EncodingUtil.base64Decode(validFor);
        return (decodedBlob.toHex().charAt(index / 4) & (1 << (index % 4))) != 0;
    }
}

Explanation

  1. The method getDependentOptions takes the object name, controlling field name, and dependent field name as inputs.
  2. It uses the DescribeFieldResult to retrieve the list of picklist entries for both fields.
  3. For each dependent field value, the validFor property is checked against the index of the controlling field value using bitwise operations.
  4. The result is a map where the key is the controlling field value, and the value is a list of valid dependent field values.

Example Usage

Map<String, List<String>> options = DependentPicklistHelper.getDependentOptions('Custom_Object__c', 'Controlling_Field__c', 'Dependent_Field__c');
for (String controllingValue : options.keySet()) {
    System.debug('Controlling Value: ' + controllingValue);
    System.debug('Dependent Values: ' + options.get(controllingValue));
}

Additional Notes

If you prefer a JavaScript-based solution for use in a Visualforce page, you can access dependent picklist information using the Salesforce AJAX Toolkit. Here’s a high-level overview:

  1. Use the sforce.connection.describeSObject method to fetch the field metadata.
  2. Parse the validFor property of each dependent picklist value.
  3. Decode the Base64 string and determine dependencies.

While this approach is similar, it works better for client-side operations and provides flexibility for integrating with Visualforce or Lightning components.

Summing Up

To retrieve dependent picklist options in Apex, you can use the DescribeFieldResult to access both controlling and dependent field values. The validFor property of each dependent picklist entry contains a Base64-encoded string, which, when decoded, indicates which controlling field options each dependent option is valid for. By using bitwise operations, you can determine the valid dependent options for each controlling field value. The solution involves iterating through the controlling field values and checking the corresponding dependent field options. This approach works within Apex and can also be adapted for client-side use with JavaScript in Visualforce pages.

Job-Oriented Salesforce Training

Our Salesforce Course is designed to deliver a thorough understanding of the Salesforce platform, equipping you with the essential skills to excel in the CRM domain. The curriculum includes key modules like Salesforce Admin, Developer, and AI, seamlessly blending theoretical concepts with practical application. With real-world project experience and hands-on exercises, you’ll develop the expertise to tackle complex business challenges using Salesforce solutions. Our seasoned instructors ensure you gain valuable technical knowledge and industry-relevant insights to thrive in the Salesforce ecosystem.

Beyond technical expertise, our Salesforce training in Chennai provides personalized mentoring, certification support, and interview coaching to enhance your career prospects. Participants benefit from comprehensive study materials, practical exposure through live projects, and individualized guidance throughout the course. By the program’s conclusion, you’ll be well-prepared not only for certification exams but also for real-world scenarios, armed with the problem-solving skills and hands-on experience employers value. Take the first step in your Salesforce career with us and open the door to a world of exciting opportunities!

The post How to Get Dependent Picklist Options in Apex? appeared first on Salesforce Online Training.


Viewing all articles
Browse latest Browse all 84

Trending Articles