Hide Options from Option Set Using JavaScript in Dynamics 365
Hide Options from Option Set Using JavaScript in Dynamics 365
Option Sets (Choice fields) are commonly used in Dynamics 365 to provide users with predefined selections. In many business scenarios, certain options need to be hidden dynamically based on user roles, field values, or business requirements.
JavaScript provides a flexible way to remove option set values at runtime, helping create a cleaner and more user-friendly experience.
Why Hide Option Set Values?
- Control user selections
- Enforce business processes
- Improve form usability
- Display context-specific options
- Reduce user errors
JavaScript Method
Use the removeOption() method to hide specific option set values from a choice field.
function hideOption(executionContext)
{
var formContext = executionContext.getFormContext();
```
formContext.getControl("new_status")
.removeOption(100000001);
```
}
The above code removes the option whose value is 100000001 from the option set control.
Hide Multiple Options
You can remove multiple values by calling removeOption() repeatedly.
function hideOptions(executionContext)
{
var formContext = executionContext.getFormContext();
```
var control = formContext.getControl("new_status");
control.removeOption(100000001);
control.removeOption(100000002);
control.removeOption(100000003);
```
}
Hide Options Based on Another Field
A common requirement is to hide option values based on another field's selection.
function filterOptions(executionContext)
{
var formContext = executionContext.getFormContext();
```
var category =
formContext.getAttribute("new_category")
.getValue();
if(category === 100000000)
{
formContext.getControl("new_status")
.removeOption(100000002);
}
```
}
Important: Register the JavaScript function on Form Load and On Change events to ensure option filtering works consistently.
Implementation Steps
- Create a JavaScript Web Resource.
- Add the script to the form.
- Register the function on Form Load.
- Pass execution context.
- Save and publish customizations.
- Test the option filtering behavior.
Common Use Cases
- Role-based option filtering
- Status-dependent choices
- Department-specific selections
- Country-specific options
- Approval process controls
- Conditional business workflows
Best Practices
- Store option values as constants when possible.
- Use executionContext instead of deprecated Xrm.Page.
- Test all business scenarios thoroughly.
- Document option values clearly.
- Avoid excessive client-side logic.
Key Takeaways
- JavaScript can dynamically remove option set values.
- removeOption() is the primary method used.
- Options can be filtered based on business logic.
- Improves user experience and data quality.
- Works effectively with Dynamics 365 and Model-Driven Apps.