How to get data by REST and display as a warning message on CRM form

Posted on Posted in JavaScript, Microsoft, MS CRM 2013, MS CRM 2015, MS Dynamics, MS Dynamics CRM, REST

In this post we are going to get an attribute value from Account entity on Order form and then display value on Order form as a Warning message (from CRM 2013 we can display wanting, info and error messages at the top rather than using alert)

First we need to get customerid from Order form

var Account = "";
Account = Xrm.Page.getAttribute("customerid").getValue();

Once we have account id we can retrieve data making a REST call

function DisplayWarning(accountid) {
SDK.REST.retrieveRecord(accountid, "Account", null, null, GetRecords, errorHandler);
}

Once we have data we can get values of attributes we are interested in
var abWarning = acc.AB_Warning;

Once we have a value and make sure its not null it can be displayed as a warning by using code below
if(abWarning!= null)
Xrm.Page.ui.setFormNotification(abWarning, 'WARNING');

Once you are done with the code, you need to add SDK.REST.js library to your form and then above code in a web resource- then call the method on load event

Below is full code


//Get warning from account for Order
function GetWarningMessageForOrder()
{
var Account = "";
Account = Xrm.Page.getAttribute("customerid").getValue();
if ((Account != null))
{
var accountId= Account [0].id;
//get data from account entity
DisplayWarning(accountId);
}
}
function DisplayWarning(accountid) {
SDK.REST.retrieveRecord(accountid, "Account", null, null, GetRecords, errorHandler);
}
function GetRecords(acc) {
var abWarning = acc.AB_Warning;

if(abWarning!= null)
Xrm.Page.ui.setFormNotification(abWarning, 'WARNING');
}
function errorHandler(error) {
alert(error.message);
}