CRM Beans

How to write and execute JavaScript in Dynamics CRM?

Spread the love

Wanted to write your first JavaScript in Dynamics CRM? This article will help you to see the things in action.

These are some of the high-level steps that you need to follow.

  1. Write a JavaScript that caters to the business issue.
  2. Add the script to the web resource.
  3. Add web resource to a form
  4. In the form events section, call the Script.

Writing a JavaScript

The first step is to identify the business case that you want to address by using the script. Once identified you need to write a JavaScript in Dynamics CRM that addresses the business issue.

Take an example if we wanted to clear the value of a field based on the selection of another field.

We write the JavaScript as:

function clearState(context)
 {
 var formContext = context.getFormContext();//
 formContext.getAttribute("logical name").setValue(null);
 }

Add JavaScript code to web resource.

Once your code is ready you can associate it with multiple events in model-driven apps.

Navigate to settings -> Customization -> Customize the system.

Open solution explorer and click web resource.

Solution Explorer

Click ‘New’ to create a new web resource.

In the web resource dialog specify Name and Display name for eg. SampleJavaScript.

In the type drop-down select Script (JScript). You can either upload the file containing JavaScript code or in the text editor window, you can write the code.

Save and publish it.

The web resource is ready now.

Associate web resource to a form.

To add the web resource on a form, open the entity in the solution explorer and click forms.

Open the main form and click form properties.

In the form properties under form libraries add web resource.

Click Add button and it will open another window where you can search the web resource.

Select the web resource and click Add to add it in the form library.

This makes the web resource available in the Event handlers section in the form Properties dialog.

In the Handler Properties, it will display all the Script in the Library section. Select the Script and in the Function text box enter the name of the function.

The script will be added in the Event Handler section of form properties dialog and based on the event selected, the script will execute.

Read: How to create a new Dynamics CRM Instance?