"use strict";
var Dys = window.Dys || {};
Dys.ValidateField = function (context) {
var data = {
"Age": context.getEventSource().getValue()
};
//dys_CheckAge is the name of the custom unbound action in this case
Dys.CallAction("dys_CheckAge", data, Dys.ValidateFieldUsingActionCallBack);
}
Dys.CallAction = function (query, data, callback) {
var url = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/" + query;
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if (this.readyState == 4) {
req.onreadystatechange = null;
if (this.status == 200) {
callback(req.response);
} else {
var error = JSON.parse(this.response).error;
alert(error.message);
}
}
};
req.send(window.JSON.stringify(data));
}
Dys.ValidateFieldUsingActionCallBack = function (response) {
alert("The value is: " + JSON.parse(response).Valid);
}
The JavaScript function “Dys.ValidateField” will be called whenever you change a custom field on a (Contact) form. This method will create a JSON object with 1 property called “Age” and then this function will call the JavaScript function “Dys.CallAction”, which will execute the Dynamics CRM action called “dys_CheckAge”. When this “Dys.CallAction” JavaScript function is finished, it will execute the JavaScript (callback) function “Dys.ValidateFieldUsingActionCallBack”, which will show the value which is returned by the Dynamics CRM action (property “Valid” of the response JSON object).
Summary
Although this example shows very simple scenario’s, the possibilities are clear:
- You are able to execute pieces of reusable (business) logic from inside or outside CRM as if it were a “custom service”.
- Althoug creating and updating CRM data is possible without using the Dynamics CRM actions as well (by simply sending a POST the the Web API), using the Dynamics CRM actions allow you to apply business logic before anything is created / updated.
- Complex business logic can be executed if you create a Custom Workflow Activity (CWA) which is used inside your Dynamics CRM action.
- A Dynamics CRM action also enables you to decouple the inside of CRM from the outside of CRM. With this I mean that you can keep your input parameters the way ther are, but do the translation (to a changed fieldname for example) in the action. This way, the outside world can reuse your action the way they are used to, while you shuffle things around within Dynamics CRM.