Lock a Field Based on Another Field in Dynamics 365
Lock a Field Based on Another Field in Dynamics 365
In Dynamics 365 and Model-Driven Apps, there are many business scenarios where a field should become read-only based on the value selected in another field.
For example, when a record reaches an Approved status, certain fields should no longer be editable. This helps maintain data integrity and enforce business processes.
Common Use Cases
- Lock fields after approval
- Prevent modifications after submission
- Restrict editing based on record status
- Control data entry based on business rules
- Improve data consistency and compliance
Using JavaScript to Lock a Field
JavaScript provides the most flexible approach for dynamically enabling or disabling form fields based on user selections.
function lockField(executionContext) {
var formContext = executionContext.getFormContext();
```
var status = formContext.getAttribute("new_status").getValue();
if(status === 100000001){
formContext.getControl("new_comments").setDisabled(true);
}
else{
formContext.getControl("new_comments").setDisabled(false);
}
```
}
Register the function on the form OnLoad event and the controlling field OnChange event.
Implementation Steps
- Create a JavaScript web resource.
- Add the script to the form.
- Create the lockField function.
- Register the function on Form Load.
- Register the function on the controlling field's On Change event.
- Save and publish customizations.
Using Business Rules
If the requirement is straightforward, Business Rules provide a no-code solution for locking fields.
- Create a Business Rule.
- Add a Condition.
- Select the controlling field.
- Add the Lock or Unlock action.
- Activate the Business Rule.
JavaScript vs Business Rules
| Feature | JavaScript | Business Rules |
|---|---|---|
| Complex Logic | Excellent | Limited |
| No-Code | No | Yes |
| Maintainability | Moderate | High |
Best Practices
- Use Business Rules for simple requirements.
- Use JavaScript for advanced logic.
- Test form behavior thoroughly.
- Document custom scripts.
- Keep field dependencies simple and maintainable.
Key Takeaways
- Fields can be dynamically locked based on other field values.
- JavaScript provides maximum flexibility.
- Business Rules offer a no-code alternative.
- Field locking improves data quality and compliance.
- Choose the approach that best fits your business requirements.