Apr.06

Using Javascript to Interact with Microsoft Dynamics CRM 2011

One of the ways you can extend Microsoft Dynamics CRM is to perform CRUD (create, read, update and delete) operations via the REST API or the SOAP API. This allows you to interact with the data within CRM with just HTML and Javascript. I recently had a project where I needed to create dialogs for the user to process records but the out-of-the-box CRM dialogs didn’t fit the bill. I was able to build out simple, light-weight and fast dialogs that allowed the user do what they needed to do.

Below are several examples of retrieving data from CRM, changing the Status (statecode) and Status Reason (statusreason) fields and associating Many-To-Many records. These examples are using the version of the Javascript SDK that relies on jQuery. Microsoft provides a version that does not rely on jQuery if you’re unable to use jQuery. ┬áThese examples where for Dynamics CRM 2011 but should point you in the right direction if you’re using CRM 2013 or 2014.

Retrieving Data

The following code allows you to retrieve multiple records from a given entity.

SDK.JQuery.retrieveMultipleRecords(
    'entityname',
    'var options = "$select=Name',
    function (values) {
        //OnSuccess callback
    },
    function (error) {
        //OnError callback
    },
    function () {
        //Fires once all data pages have been retrieved.
    });

The filter can be tweaked to match how you are trying to retrieve values. For example, the following filter is matching the School ID value, the Student Name ID value, the Degree optionset value and the Status (statecode) value. This filter would just replace ‘var options = “$select=Name’ in the above example. You can test your filter strings by hitting the OData service over a browser and examining the results.

"$filter=pt_School/Id eq (Guid'" + schoolId + "') and pt_StudentName/Id eq (Guid'" + studentId + "') and pt_Degree/Value eq " + degreeValue + " and statecode/Value eq 0"

 

Creating Records

The process to create a record looks somewhat similar to retrieving records. However, we create a simple Javascript object to contain the field values for the new record and pass that into the createRecord call.

There are a couple things to note here:

  1. Make sure that the names of the object’s properties match the schema names of the fields you’re populated on the entity.
  2. If you’re trying to set the value of an Optionset field, use the numerical value that CRM assigned to the option.
var myNewRecord= {};
historyRecord.name = 'John';
historyRecord.description = 'This is my description';
historyRecord.fieldA = 'Contents for FieldA';
historyRecord.fieldB = 'Contents for FieldB';

SDK.JQuery.createRecord(
    historyRecord,
    'entityname',
    function (record) {
        //OnSuccess Callback
    },
    function (error) {
        //OnError Callback
    });

Updating Records

To update an existing record, you’ll need the GUID value of the record and you’ll need to create a Javascript object just like when you create a new record. However, you only need to add the fields you’re changing to the Javascript object. Make sure that the object’s property names match the schema names of the fields.

var updatedRecord = {};
updatedRecord .FieldA = 'New value for FieldA';
updatedRecord .FieldB = 'New value for FieldB';

SDK.JQuery.updateRecord(
    currectRecordId,
    updatedRecord,
    'entityname',
    function () {
        //OnSuccess Callback
    },
    function () {
        //OnError Callback
    });

Associating Records

You can also associate records via the REST/OData API.

SDK.JQuery.associateRecords(
    "parentId",
    "parentEntityName",
    "relationshipName",
    "childId",
    "childEntityName",
    function () {
        //OnSuccess Callback
    },
    function (error) {
        //OnError Callback
});

Changing the Status and Status Reason

It is possible to change the Status (statecode) and Status Reason (statuscode) from Javascript. However, it can’t be done via the Rest/OData API. You have to build a SOAP envelope and submit it to the service at “/XRMServices/2011/Organization.svc/web”.

SDK.JQuery.SetStateRequest(
    1, //Status (statecode)
    206300005, //Status Reason (statuscode)
    'entityName', 
    currentRecordId, 
    function () {
        //OnSuccess Callback
    }
);

//Building the SOAP envelope
SetStateRequest: function (newStateCode, newStatusCode, entityName, entityId, successCallback) {
     
var requestMain = ""
requestMain += "";
requestMain += "  ";
requestMain += "    ";
requestMain += "      ";
requestMain += "        ";
requestMain += "          ";
requestMain += "            EntityMoniker";
requestMain += "            ";
//Setting Record Id Guid
requestMain += "              " + entityId + "";
//Setting Entity Name
requestMain += "              " + entityName + "";
requestMain += "              ";
requestMain += "            ";
requestMain += "          ";
requestMain += "          ";
//Setting StateCode (Status)
requestMain += "            State";
requestMain += "            ";
requestMain += "              " + newStateCode + "";
requestMain += "            ";
requestMain += "          ";
requestMain += "          ";
//Setting StatusCode (Status Reason)
requestMain += "            Status";
requestMain += "            ";
requestMain += "              " + newStatusCode + "";
requestMain += "            ";
requestMain += "          ";
requestMain += "        ";
requestMain += "        ";
requestMain += "        SetState";
requestMain += "      ";
requestMain += "    ";
requestMain += "  ";
requestMain += "";
     
var req = new XMLHttpRequest();
    
req.open("POST", "http://adm-v-dcrm01/PokagonDev/XRMServices/2011/Organization.svc/web", true)
// Responses will return XML. It isn't possible to return JSON.
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
//var successCallback = null;
var errorCallback = null;
req.onreadystatechange = function () { SDK.JQuery.SetStateResponse(req, successCallback, errorCallback); };
req.send(requestMain);
Dynamics CRM