Get and Set value using ODATA End Points

Below is a sample code which gets data from a custom entity by passing name of the record –

In code below, I am triggering function ‘CheckAndSetOutcode’ on change of a field on a form (post code in this case)

First trim post code (you can just pass name if needed to)

Once I have formatted data I will pass it to query to get data back

Once I retrieve data, i am setting value of an other field on Account form
// Determine outcode
function CheckAndSetOutcode()
{
var Outcode = "";
var Postcode = "";
var Length = "";

Postcode = Xrm.Page.getAttribute(“address1_postalcode”).getValue();
Postcode = Postcode.replace(” “, “”);

switch (Postcode.length)
{
case 5:
Length = 2;
break;
case 6:
Length = 3;
break;
case 7:
Length = 4;
break;

default:
Length = 0;
break;
}

if (Length == 0)
{
alert(“Outcode cannot be determined, manually set!”);
}
else
{
Outcode = Postcode.substring(0, Length);
SetOutcode(Outcode);
}
}

function retrieveMultiple(odataSetName, filter, successCallback, errorCallback, _executionObj) {
_executionObjMultiretrive = _executionObj;
var context = Xrm.Page.context;
var serverUrl = context.getServerUrl();
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
if (!odataSetName) {
alert(“odataSetName is required.”);
return;
}

var odataUri = serverUrl + ODATA_ENDPOINT + “/” + odataSetName;

if (filter) {
odataUri += filter;
}

$.ajax({
type: “GET”,
async: false,
contentType: “application/json; charset=utf-8”,
datatype: “json”, url: odataUri,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
},
success: function (data, tStatus, XmlHttpRequest) {
if (successCallback) {
if (data && data.d && data.d.results) {
successCallback(data.d.results, tStatus, XmlHttpRequest);
}
else if (data && data.d) {
successCallback(data.d, tStatus, XmlHttpRequest);
}
else {
successCallback(data, tStatus, XmlHttpRequest);
}
}
},
error: function (XmlHttpRequest, tStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, tStatus, errorThrown);
else
errorHandler(XmlHttpRequest, tStatus, errorThrown);
}
});
}
function errorHandler(xmlHttpRequest, tStatus, errorThrow) {
alert(“Error : ” + tStatus + “: ” + xmlHttpRequest.statusText);
}

function SetOutcode(outcode) {
var _condition= “multiple retrieve with odata”;
if (_condition!= null) {
retrieveMultiple(“new_mycustomentitySet”, “?$filter=new_name eq ‘”+outcode+”‘&$top=1”, GetRecords, null, null);
}
}

function GetRecords(data, tStatus, XmlHttpRequest) {
if (data.length > 0) {
for (i = 0; i < data.length; i++) {
var abcId = data[i].new_mycustomentityId;
var abcName = data[i].new_name;

var lookup = new Array();
lookup[0] = new Object();
lookup[0].id = abcId;
lookup[0].name = abcName.toUpperCase();
lookup[0].entityType = "new_mycustomentity";
Xrm.Page.getAttribute("new_mycustomentityid").setValue(lookup);
}
}
}

Comments are closed.