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

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

  1. Create a JavaScript web resource.
  2. Add the script to the form.
  3. Create the lockField function.
  4. Register the function on Form Load.
  5. Register the function on the controlling field's On Change event.
  6. Save and publish customizations.
Important: Always pass the execution context when registering JavaScript functions in Dynamics 365 forms.

Using Business Rules

If the requirement is straightforward, Business Rules provide a no-code solution for locking fields.

  1. Create a Business Rule.
  2. Add a Condition.
  3. Select the controlling field.
  4. Add the Lock or Unlock action.
  5. 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

Key Takeaways