How to add JavaScript event to Dynamics 365 Form

How to add JavaScript to form on load in Dynamics 365

If you think your friends/network would find this useful, please share it with them – I’d really appreciate it.

How to add a JavaScript event to a form in Dynamics 365. Step by step guide using the Power Apps admin center.

Step 1: Go to https://make.powerapps.com

Step 2: Go to the right environment. By changing the environment in the top right corner.

Step 3: Go to Dataverse in the side menu.

Step 4: Click on Tables.

Step 5: Go to the table you want to edit. In this example the Contact table.

Step 6: Find the form on the table you want to add the JavaScript to. In this case the main for on the contact.

Step 7: Open the form in edit mode.

Step 8: Add web resource. By clicking the folder in the side menu and + Add Library.

If you already have a script you can add it from this view, and when you need to create a new script you need to add it as a new web resource. In this post we look at how to create a new script as a web resource.

Step 9: Create a new web resource. Give it a Name, Display Name, Description, Type (Script – JScript), add File or use Text editor to add a function.

Editing the JavaScript code in the text editor. Open Text Editor and add your code. Click OK to proceed the creation of the Web Resource.

Ooops.. Script error in the image above. The correct script in the example is the following:

function mainContactFormOnLoad(executionContext) {
    const formContext = executionContext.getFormContext();
    let firstName = formContext.getAttribute("firstname").getValue();

    alert("Hello " + firstName);
}

The script opens a dialog with “Hello” and the name of the contact when the form is loaded. As an example to show the on load event.

Step 10: Save and Publish the Web Resource.

Step 11: Go back to the contact form and add the web resource you created by searching for it and add it to the list. Now we can add the script to an event on the form.

Step 12: In this post we add a function to the on load event. Click on + Event Handler.

Step 13: Add Event Type, Library, Function (name of the function in your code) and Pass execution context as first parameter and click Done.

The screenshot below show how it looks and what the pass execution context parameter looks like.

Step 14: Now that we have added the event to the form the remaining steps is saving and publishing the form and to see that the script runs when opening the main contact form in your Dynamics App. Save first and then Publish.

Step 15: Open the form in your and and see the result. The script runs when the form loads or refreshes.

Hope you found the post useful.