Dependent option sets using JavaScript in Model Driven Apps

Tamilarasu Arunachalam
3 min readJul 25, 2023

--

Photo by dylan nolte on Unsplash

Dependent Option sets

Option sets which depend on the another option set, and the options vary on the change of the value in parent option set.

We can add options to option sets dynamically using client side scripting. Here I have a scenario of two option set fields, Qualification and Degree. Here, Degree is the dependent on the Qualification.

The Qualification field contains two options, UG and PG. The Degree field contains the below options with values as listed in the below table.

Here we need to make the options of degree field dependent on the selected value from qualification field. I need to create a JavaScript code to demonstrate the same. I have used an object which contains options respective to the qualification. The object is in the below snippet.

Note: It is better you can add the same handler to on-load event to prevent inconsistency issues.

{
"UG": [
{ value: 0, text: "BA" },
{ value: 1, text: "BSC" },
{ value: 2, text: "BCA" },
{ value: 3, text: "BBA" },
{ value: 4, text: "BCOM" }
],
"PG": [
{ value: 5, text: "MA" },
{ value: 6, text: "MSC" },
{ value: 7, text: "MCA" },
{ value: 8, text: "MBA" },
{ value: 9, text: "MCOM" }
]
}

I have used the below JavaScript code for making the dependent option sets

function dependentOptionsets(formContext) {
// getting form context
formContext = formContext.getFormContext();
//Options Object
var optionset = {
"UG": [
{ value: 0, text: "BA" },
{ value: 1, text: "BSC" },
{ value: 2, text: "BCA" },
{ value: 3, text: "BBA" },
{ value: 4, text: "BCOM" }
],
"PG": [
{ value: 5, text: "MA" },
{ value: 6, text: "MSC" },
{ value: 7, text: "MCA" },
{ value: 8, text: "MBA" },
{ value: 9, text: "MCOM" }
]
};

var parentOptionset = formContext.getAttribute("crf4c_one").getText();
var childOptionset = formContext.getControl("crf4c_two");

// add options based on the parent optionset
switch (parentOptionset) {
case 'UG':
childOptionset.clearOptions();
optionset.UG.forEach(element => {
childOptionset.addOption(element);
});
break;
case 'PG':
childOptionset.clearOptions();
optionset.PG.forEach(element => {
childOptionset.addOption(element);
});
break;
case null:
childOptionset.clearOptions();
break;
}
}

For that, I have to set the on-change event on the qualification field and add the JavaScript to the event handler.

Save and Publish the form. Navigate to the form to check the script. The GIF is attached below.

Have a good day!

Originally published at https://www.tamilarasu.me on July 25, 2023.

--

--

Tamilarasu Arunachalam

A Software Engineer with experience in developing applications out of Power Platform, majorly on Power Apps and Power Automate. I am a seasonal blogger too.