Sunday, May 27, 2012

Retrieve the related entity Data using Javascript (json)

 In this example it will retrieve the related sales order detail for a specific sales order ..

 retirevesalesorderdetails :function () {
 var GUIDvalue = Xrm.Page.data.entity.getId();
 var serverUrl = Xrm.Page.context.getServerUrl();
 var req = new XMLHttpRequest(); req.open("GET", serverUrl +   "/XRMServices/2011/OrganizationData.svc/SalesOrderSet(guid'" + GUIDvalue + "')/order_details", true); //order_details is the relationship with the sales order and sales order details
  req.setRequestHeader("Accept", "application/json");
  req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  req.onreadystatechange = function () {
     if (this.readyState == 4 /* complete */) {
            if (this.status == 200) {
                        var returned = JSON.parse(this.responseText,_dateReviver).d;
                        successCallback(returned.results);
                         if (returned.__next != null) { }
                         else { OnComplete(); } }
                         else { errorCallback(_errorHandler(this)); }
                   }
               };
     req.send();
 }


_dateReviver: function (key, value) {
    ///


    /// Private function to convert matching string values to Date objects.
    ///

    ///

    /// The key used to identify the object property
    ///
    ///

    /// The string value representing a date
    ///
    var a;
    if (typeof value === 'string') {
        a = /Date\(([-+]?\d+)\)/.exec(value);
        if (a) {
            return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
        }
    }
    return value;
}
function errorHandler(error) {
    writeMessage(error.message);
}
function successCallback(results) {
    for (var i = 0; i <= results.length; i++) {
        var Result = results[i];
        if (Result != null) {      
            var ProductId = Result.tci_productid;
            var SalesQty = Result.quantity;
  }
 }
}

function OnComplete() {
    //OnComplete handler
}

Note :- in this you have to add the json2.js libaray also for the parsing to happen .. it is available with CRM 2011 SDK

3 comments: