Thursday, 28 December 2017

Filter Option Sets in Dynamics CRM using Javascript

Introduction:
Suppose you have an Option set field named "optionSetField" that needs to show different values when field "optionSetFilterField" value is 1, and when field "optionSetFilterField" value is 2, it needs to show different values. This requirement can easily be achieved using JavaScript

Solution:
Create a new Web resource as shown below





In the Text Editor, paste the following JavaScript

function filterOptionSets() {
    //get option set control and its options
    var optionsetControl = Xrm.Page.ui.controls.get("optionSetField");
    var options = optionsetControl.getAttribute().getOptions();

    //get the field value on which bases the option set needs to be filtered
    var filterValue = Xrm.Page.getAttribute("optionSetFilterField").getValue();

    //get current selected value of option set
    var currentValue = Xrm.Page.getAttribute("optionSetField").getValue();

    //based on the filterValue, clear option set and then add the required options
    if (filterValue = 1) {
        optionsetControl.clearOptions();
        optionsetControl.addOption(options[0]);
        optionsetControl.addOption(options[1]);
        optionsetControl.addOption(options[2]);
    }
    else if (filterValue = 2) {
        optionsetControl.clearOptions();
        optionsetControl.addOption(options[3]);
        optionsetControl.addOption(options[6]);
    }
    else if (filterValue = 3) {
        optionsetControl.clearOptions();
        optionsetControl.addOption(options[4]);
        optionsetControl.addOption(options[5]);
        optionsetControl.addOption(options[7]);
    } 
   
    //if a value in option set field was already selected, re-set the previous value
    if (currentValue != null)
        Xrm.Page.getAttribute("optionSetField").setValue(currentValue);
}

//this method needs to be configured on "optionSetFilterField" field OnChange event
function onFieldChange() {
    Xrm.Page.getAttribute("optionSetField").setValue(null);
    filterOptionSets();
}

//this method needs to be configured on Form OnLoad event
function onFormLoad() {
    filterOptionSets();
}


Now, navigate to the Form Properties on the form where Option set control needs to be filtered and add the above created Web resource






Now set the Event Handlers as shown in the following images





Save the form and Publish the customization to start using the functionality!

No comments:

Post a Comment