Filter Option sets by another field in Dynamic CRM 2011

Zhen Yuwang, 18 January 2012

To hide or show some options of an option set based on another field is not very difficult in Dynamic CRM 2011.

To start, we have two option sets, one is the customer type and the other is phone type.

 Filter Option sets by another field in Dynamic CRM 2011

Filter Option sets by another field in Dynamic CRM 2011

So every time the “Customer” option set changes we want the “Phone” option set to change. We can achieve this by writing a simple javascript function.

optionSetChanged = function () {
    var optionsetControl = Xrm.Page.ui.controls.get("mag_phones");
    var options = optionsetControl.getAttribute().getOptions();

     var type = Xrm.Page.getAttribute("mag_types").getValue();
    // 'Account' is selected
    if (type == 809730000) {
        optionsetControl.clearOptions();
        for (var i = 0; i < options.length - 1; i++) {
            if (i == 0 || i == 1) {
                optionsetControl.addOption(options[i]);
            }
        }
    }
    // 'Contact' is selected
    else if (type == 809730001) {
        optionsetControl.clearOptions();
        for (var i = 0; i < options.length - 1; i++) {
            if (i == 2 || i == 3 || i == 4) {
                optionsetControl.addOption(options[i]);
            }

        }
    }
} 

To add it as a Script (JScript) under Web Resources go to “Settings” -> “Customization” -> “Customize the System” -> “Web Resource” -> ”New”. Set the “Name”, “Display Name” and “Type”. Copy paste the JavaScript into “Text Editor” then Save and Close.

 Filter Option sets by another field in Dynamic CRM 2011

Set it at Form OnLoad event. Open Main Form of the Entity. Click “Form Properties”. Add “Form Libraries” and “Event Handlers” like this:

 Filter Option sets by another field in Dynamic CRM 2011

Also set “Customer” Option set OnChange event.

 Filter Option sets by another field in Dynamic CRM 2011

Save and close, publish all customizations, refresh IE window.

The final result is like this:

Filter Option sets by another field in Dynamic CRM 2011

 Filter Option sets by another field in Dynamic CRM 2011