microsoft-dynamics-crm-js

This blog post will cover how to set up JavaScript for a form in Microsoft Dynamics CRM in detail and how to construct your scripts to do what you want.

The Challenge

Recently, a customer came to us with a request. They had created a custom entity that had look-ups (N:1 relationships) to a contact and an account with a primary contact along with a custom workflow that triggers an email to be sent to those two contacts. They wanted us to create two read-only fields that were populated with the contact’s email and the primary contact’s email. This was to allow their staff users to verify that the two records did in fact have emails before running the workflow without opening the related records. To accomplish this, we added JavaScript to the form to populate these fields on load and on save of the form.

Need Dynamics CRM or D365 Hosting?

Cobalt has 3 different hosting packages and 15+ years of hosting and Dynamics expertise.

Review Our Hosting Packages

Uploading a Script to CRM

Now let’s get to work. To upload a script to CRM, first navigate to the entity in question’s form and select Form Properties. You will be putting your JavaScript under the Form Libraries section. Select Add and fill out the fields necessary. After adding the script, navigate to Event Handlers. Here we can specify what function is called from which library for each of the specified events – on load and on save. Parameters for these functions can also be specified.

Here is the script I created to meet my customer’s business requirements.

function setContactEmail(){

//Get the contact lookup off of the record
var contact = Xrm.Page.getAttribute('cobalt_contactid').getValue();

//if contact exist, attempt to pull back the entire contact record
if(contact != null && contact[0].entityType == "contact")
{

var contactId = contact[0].id;
var serverUrl;

if (Xrm.Page.context.getClientUrl !== undefined) {
serverUrl = Xrm.Page.context.getClientUrl();
}
else {
serverUrl = Xrm.Page.context.getServerUrl();
}

var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var contactRequest = new XMLHttpRequest();

contactRequest.open("GET", ODataPath + "/ContactSet(guid'" + contactId + "')", false);
contactRequest.setRequestHeader("Accept", "application/json");
contactRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");

contactRequest.send();
//If request was successful, parse the email address
if(contactRequest.status == 200)
{

var retrievedContact = JSON.parse(contactRequest.responseText).d;
var contactEmail = retrievedContact.EMailAddress1;

if(contactEmail != null)
{
//set the value of the contacts email to the field “cobalt_contactsemail”
Xrm.Page.getAttribute('cobalt_contactsemail').setValue(contactEmail);
}
else
{
//Default message for when the contact has no email.
console.log('contact email not set');
Xrm.Page.getAttribute('cobalt_contactsemail').setValue("---No Email on Contact---");

}

}
else
{
console.log('request failed.');
Xrm.Page.getAttribute('cobalt_contactsemail').setValue("---No Contact Found---");
}

}
else
{
console.log('no contact on the form.');
Xrm.Page.getAttribute('cobalt_contactsemail').setValue("");
}

Xrm.Page.getAttribute('cobalt_contactsemail').setSubmitMode("always");
}

The above is the snippet of JavaScript that was used to set the cobalt_contactsemail field on the form, which is where we chose to store the contact’s email address.  Lookups on forms only contain three properties that pertain to that lookup, which are the name, the ID and the entity type. Using this contact’s ID, we sent a request back to CRM to get the entire contact record. The request comes back with a JSON object containing a contact. Then the email is parsed from the contact record and set to the corresponding contact email on the record. We used a similar process to get the account’s primary contact email, with one difference: the account was pulled from the account lookup and then the primary contact was pulled from that request.

Note: This example is of a solution that was meant to solve a specific customer challenge. Please remember that these read-only fields should not be used for anything other than to view while looking at a record. This is because the fields are only updated when a particular record is opened and saved, so they are not updated when the related records are updated. If you wanted these fields to be updated when the corresponding records’ emails are updated, I would recommend plugins or workflows to set the text fields.

I hope that this example shows how powerful JavaScript can be in Microsoft CRM. It allows you to quickly deploy business logic to your CRM deployment without having to compile custom code and deploy plugins. The ability to retrieve data through JSON opens up unlimited possibilities and makes this a powerful option when crafting a solution to meet your customers’ needs.

Considering a CRM Migration?

If your team is considering a CRM migration in the next few years, we’ve got resources for you that pull together the best of what we’ve learned through 26+ years of CRM expertise.

And, take a copy of our CRM Cloud Migration ebook with you today. You team will find even more helpful questions and considerations as you plan for your next CRM migration project. Let us know if we can help!