Trigger JavaScript on Form Load, Save, and Field Change in Dynamics 365

Power Dynamite
2 min readFeb 24, 2025

--

Introduction

When working with Dynamics 365, you often need to automate actions based on form events. JavaScript allows us to execute custom logic when a form is loaded, saved, or when a field value changes. This article will guide you through implementing JavaScript event handlers in Dynamics 365.

Events in Dynamics 365 Forms

Dynamics 365 provides several client-side events that can be leveraged using JavaScript:

  • OnLoad — Triggered when the form loads.
  • OnSave — Triggered when the form is saved.
  • OnChange — Triggered when a field value is modified.

Step 1: Writing JavaScript Functions

1. Trigger JavaScript on Form Load

To execute a script when the form loads, use the OnLoad event. This is useful for setting default values, hiding/showing fields, or performing other actions when a record is opened.

function onFormLoad(executionContext) {
var formContext = executionContext.getFormContext();
// Example: Display an alert message on form load
alert("Welcome to Dynamics 365!");

// Example: Set a field value
formContext.getAttribute("description").setValue("This is a prefilled value.");
}

2. Trigger JavaScript on Form Save

To execute logic before saving a record, use the OnSave event. This can be used to validate fields or prevent saving under certain conditions.

function onFormSave(executionContext) {
var formContext = executionContext.getFormContext();
var nameField = formContext.getAttribute("name").getValue();

// Example: Prevent save if name field is empty
if (!nameField) {
alert("Name field cannot be empty!");
executionContext.getEventArgs().preventDefault();
}
}

3. Trigger JavaScript on Field Change

To execute logic when a field value changes, use the OnChange event. This is useful for real-time validations or updating other fields based on user input.

function onFieldChange(executionContext) {
var formContext = executionContext.getFormContext();
var newValue = formContext.getAttribute("accountnumber").getValue();

// Example: Show an alert when account number changes
if (newValue) {
alert("Account number changed to: " + newValue);
}
}

Step 2: Registering JavaScript Functions in Dynamics 365

To attach these functions to form events:

  1. Navigate to Power Apps > Solutions and open your entity form.
  2. Click on Form Properties.
  3. Add a new JavaScript Web Resource and include your script.
  4. Under the Events tab, add the respective functions to OnLoad, OnSave, or OnChange events.
  5. Save and publish the changes.

Conclusion

Using JavaScript to handle form events enhances the user experience by automating field updates, enforcing validation rules, and providing dynamic behavior. With the above examples, you can efficiently manage form events in Dynamics 365.

Stay tuned for more articles on Dynamics 365 JavaScript implementation!

--

--

No responses yet