Walkthrough: Write your first client script
Ready to write your first client script to see things in action. Lets get started; we'll keep it simple.
Objective
After completing this walkthrough, you will know how to use your JavaScript code in model-driven apps, which involves the following steps at a high level:
- Write your JavaScript code to address a business issue
- Upload your JavaScript code as a web resource in model-driven apps
- Associate the JavaScript functions in the web resource to different client-side events in model-driven apps.
We will draw your attention to important facts during the walkthrough, and provide references to actual methods as appropriate.
Step 1: Write your custom JavaScript code
The first step is to identify the business issue you are trying to address using client scripting. Once you have identified it, you need to write your JavaScript code containing the custom business logic that addresses your business issue.
Model-driven apps do not provide a JavaScript editor. So, you can use an external authoring tool that provides features to specifically support editing JavaScript files, such as Notepad++, Visual Studio Code, or Microsoft Visual Studio.
You can review the complete sample code used in the walkthrough later in this article.
Let's look at the code in detail:
Detailed code explanation
Define namespace: The code starts by defining a namespace for your custom script. As a best practice, you should always create namespaced JavaScript libraries to avoid having your functions overridden by functions in another library.
var Sdk = window.Sdk || {};In this case, all the functions defined in this library can be used as
Sdk.[functionName].Define global variables: The following section defines some global variables to be used in the script. You now don't need to go through the form context to get the user name. Context information is now available globally using the Xrm.Utility.getGlobalContext method.
// Define some global variables var myUniqueId = "_myUniqueId"; // Define an ID for the notification var currentUserName = Xrm.Utility.getGlobalContext().userSettings.userName; // get current user name var message = currentUserName + ": Your JavaScript code in action!";Code to execute on the OnLoad event: This section contains the code that will be executed when the account form loads. For example, when you create a new account record or when you open an existing account record.
The code uses the
executionContextobject to get theformContextobject. When we attach our code with the form event later, we will remember to select the option to pass the execution context to this function. Next, we display a form level notification using the setFormNotification method. Next, we use the setTimeOut method to delay the execution of the clearFormNotification method to clear the notification after 5 seconds.// Code to run in the form OnLoad event this.formOnLoad = function (executionContext) { var formContext = executionContext.getFormContext(); // display the form level notification as an INFO formContext.ui.setFormNotification(message, "INFO", myUniqueId); // Wait for 5 seconds before clearing the notification window.setTimeout(function () { formContext.ui.clearFormNotification(myUniqueId); }, 5000); }Code to execute on the OnChange event: Code in this section will be associated with the Account Name column in the account form so that it gets executed only when you change the account name value.
The code performs a case-insensitive search for "Contoso" in the account name, and if present, automatically sets values for some columns in the account form.
// Code to run in the column OnChange event this.attributeOnChange = function (executionContext) { var formContext = executionContext.getFormContext(); // Automatically set some column values if the account name contains "Contoso" var accountName = formContext.getAttribute("name").getValue(); if (accountName.toLowerCase().search("contoso") != -1) { formContext.getAttribute("websiteurl").setValue("https://www.contoso.com"); formContext.getAttribute("telephone1").setValue("425-555-0100"); formContext.getAttribute("description").setValue("Website URL, Phone and Description set using custom script."); } }Code to execute on the OnSave event: The code in this section displays an alert dialog box using the openAlertDialog method. This dialog box displays a message with the OK button; user can close the alert by selecting OK.
We are not passing in the execution context in this function as it's not required to execute Xrm.Utility. methods.
// Code to run in the form OnSave event this.formOnSave = function () { // Display an alert dialog Xrm.Navigation.openAlertDialog({ text: "Record saved." }); }
Step 2: Add your JavaScript code in a Script web resource
Now that your code is ready, you want to associate it with events in model-driven apps. You use Script web resources in model-driven apps to upload the script to your model-driven apps instance, and then associate it with events.
Navigate to Power Apps.
In the left navigation pane, select Data and then select Tables.
From the list of tables, select the table where you want to add the JavaScript web resource.
Select Forms tab, and then from the list of forms select the desired form.

Select Form libraries from the left navigation pane and then select Add library.

Select New to create a JavaScript web resource.
In the new web resource dialog, specify the Name and Display Name for your web resource. For example: "mySampleScript.js" and "Sample: Walk through" Script.
Select Script (JScript) from the Type drop-down list. You can either upload a file containing your JavaScript code by selecting Choose File, or select Text Editor and then paste your JavaScript code in the editor.

Select Save to create the web resource containing your JavaScript code.
Select Publish to publish your web resource.
Step 3: Associate Script web resource to a form
Go to Power Apps.
In the left navigation pane, select Data and then select Tables.
From the list of tables, select the table where you want to add the event handlers.
Select Forms tab from the command bar and then select the form where you want to add.

Select Events tab. You'll notice that both the On Save and On Load event handlers.

Select
OnLoadevent handler and associate the function you want to achieve.
Select
OnSaveevent handler and associate the function you want to achieve.
If you wish to add the event handler for the on change event, select the column and then select Event tab.

That's it! You have completed the steps to configure the account form to use custom business logic specified in your JavaScript code.
Test your JavaScript code
It is recommended that you refresh your browser for the changes to take effect in your model-driven apps instance. To test custom business logic you configured in this walk through:
Sign in to your model-driven apps instance.
Browse to Accounts, and try to open or create a new account. In this case, we will open an existing account to load the account form. You will see a notification containing your user name that will automatically disappear in 5 seconds.

Edit the account name to add "Contoso" in the name and move to the next column by pressing TAB. This will fire the OnChange event, and will automatically update the Phone, Website, and Description columns with the value specified in the code.

Finally selecting Save will fire the OnSave event, and will display the alert dialog with a message that you configured in your code. Select OK to close the alert.

Complete sample code used in the walk through
// A namespace defined for the sample code
// As a best practice, you should always define
// a unique namespace for your libraries
var Sdk = window.Sdk || {};
(function () {
// Define some global variables
var myUniqueId = "_myUniqueId"; // Define an ID for the notification
var currentUserName = Xrm.Utility.getGlobalContext().userSettings.userName; // get current user name
var message = currentUserName + ": Your JavaScript code in action!";
// Code to run in the form OnLoad event
this.formOnLoad = function (executionContext) {
var formContext = executionContext.getFormContext();
// display the form level notification as an INFO
formContext.ui.setFormNotification(message, "INFO", myUniqueId);
// Wait for 5 seconds before clearing the notification
window.setTimeout(function () { formContext.ui.clearFormNotification(myUniqueId); }, 5000);
}
// Code to run in the column OnChange event
this.attributeOnChange = function (executionContext) {
var formContext = executionContext.getFormContext();
// Automatically set some column values if the account name contains "Contoso"
var accountName = formContext.getAttribute("name").getValue();
if (accountName.toLowerCase().search("contoso") != -1) {
formContext.getAttribute("websiteurl").setValue("https://www.contoso.com");
formContext.getAttribute("telephone1").setValue("425-555-0100");
formContext.getAttribute("description").setValue("Website URL, Phone and Description set using custom script.");
}
}
// Code to run in the form OnSave event
this.formOnSave = function () {
// Display an alert dialog
Xrm.Navigation.openAlertDialog({ text: "Record saved." });
}
}).call(Sdk);








