Tuesday, December 3, 2013

JavaScript Retrieve, Retrieve Multiple Records CRM 2011 and CRM 2013 Using OData End point with JavaScript and jQuery

The OData endpoint lets you interact with Microsoft Dynamics CRM 2013 and Microsoft Dynamics CRM Online data by using JavaScript libraries. You create script web resources using files defining the JavaScript libraries. Then you associate functions in the libraries with form or field event handers or ribbon command actions. You can use them as you would any other JavaScript library within webpage (HTML) web resources.

Ajax

AJAX (Asynchronous JavaScript and XML) is a web development technique used to create interactive web applications. Server requests are made from the browser in the background using an XmlHttpRequest object. While you can send synchronous requests, the recommended practice is to send asynchronous requests. Asynchronous requests require two JScript functions, one to send the request and a second “callback” function to process a response.

JSON

JavaScript Object Notation (JSON) format is used for serializing and transmitting structured data much in the same way that XML is typically used. Like XML, it is text based and designed to be readable by humans. To convert regular JavaScript objects into the JSON format you use the JSON.stringify method. Because the text in JSON defines JavaScript objects, the text could be converted to JavaScript objects by using the eval method. However, this practice creates security vulnerabilities. You should use the JSON.parse method instead.

XmlHttpRequest

XmlHttpRequest (sometimes referred to as XHR) provides capabilities to configure and send requests and define a callback function if the request is asynchronous. The HTTP response from the server includes a status code indicating whether the request was successful. HTTP status code values in the 200 range are considered successful.
An XmlHttpRequest provides instructions to the server about the format of any data to be included in the response. Because the ODATA endpoint supports both ATOM and JSON formats you have the option to request data to be returned in the XML ATOM format. However, with JavaScript code the expected typical request will use JSON because it is easily consumable using JavaScript.

Add the JSon and jQuery Library on the Form:
json and jQuery files can be found from SDK - SampleCode - JS - RestEndpoint - jQueryRestDataOperations - Script

function CallingRetrieveFuncation(){

var accountId = "65E575CE-AF52-E311-A085-6C3BE5A8C054"; // Assign account GUID

var odataSetName = "AccountSet";

retrieveRecord(accountId,odataSetName );

}

function retrieveRecord(id, odataSetName) {

// Get Server URL

var serverUrl = Xrm.Page.context.getServerUrl();

//The OData end-point

var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/";

//Asynchronous AJAX function to Retrieve a CRM record using OData

$.ajax({

type: "GET",

contentType: "application/json; charset=utf-8",

datatype: "json",

url: serverUrl + ODATA_ENDPOINT + odataSetName + "(guid'" + id + "')",

beforeSend: function (XMLHttpRequest) {

//Specifying this header ensures that the results will be returned as JSON.

XMLHttpRequest.setRequestHeader("Accept", "application/json");

},

success: function (data, textStatus, XmlHttpRequest) {

readRecord(data, textStatus, XmlHttpRequest)

},

error: function (XmlHttpRequest, textStatus, errorThrown) {

alert("Error – " + errorThrown)

}

});

}

function readRecord(data, textStatus, XmlHttpRequest) {

alert("Record read successfully!!");

var account = data;

alert("Name – " + account.d.Name);

alert("Id – " + account.d.AccountId);

}

SDK Reference:

function retrieveAccount(AccountId) {
 SDK.JQuery.retrieveRecord(
     AccountId,
     "Account",
     null, null,
     function (account) {
      writeMessage("Retrieved the account named \"" + account.Name + "\". This account was created on : \"" + account.CreatedOn + "\".");
      updateAccount(AccountId);
     },
     errorHandler
   );
}
 
function retrieveAccounts() {
   ///<summary>
   /// Retrieves accounts by passing a filter to the SDK.RestEndpointPaging.RetrieveRecords function
   ///</summary>
   clearaccountsGrid();
   var number = parseInt(numberOfAccountsToRetrieve.options[numberOfAccountsToRetrieve.selectedIndex].value, 10);
   var options = "$select=Name,Telephone1&$top=" + number;
   //The retrieveAccountsCallBack function is passed through as the successCallBack.
   SDK.REST.retrieveMultipleRecords("Account", options, retrieveAccountsCallBack, function (error) { alert(error.message); }, accountsRetrieveComplete);
  }
  function retrieveAccountsCallBack(retrievedAccounts) {
   ///<summary>
   /// This function is passed through the request and is iterated for each page of data
   /// This function appends rows to the accountsGrid.
   ///</summary>
   totalAccountCount = totalAccountCount + retrievedAccounts.length;
   for (var i = 0; i < retrievedAccounts.length; i++) {
    var account = retrievedAccounts[i];
    var row = document.createElement("tr");
    var nameCell = document.createElement("td");
    setElementText(nameCell, account.Name);
    row.appendChild(nameCell);
    var mainPhoneCell = document.createElement("td");
    setElementText(mainPhoneCell, (account.Telephone1 == null) ? "" : account.Telephone1);
    mainPhoneCell.className = "rightColumn";
    row.appendChild(mainPhoneCell);
    accountsGrid.appendChild(row);
   }
  }

function accountsRetrieveComplete() {
   ///<summary>
   /// This function is called after all the records have been returned to update the actual total number of records.
   ///</summary>
   accountsRetrieved.innerText = totalAccountCount;
   successMessage.style.display = "block";
  }
For the following CRM attributes there is more involved. OptionSet Money DateTime var  _territorycodeOptionSet = account.d.territorycode.Value; /*      For Retrieving Lookup Values    */ var olookup = new Object(); olookup.id = account.d.ParentAccountId.Id; olookup.entityType = "account"; olookup.name = account.d.ParentAccountId.Name; var olookupValue = new Array(); olookupValue[0] = olookup; Xrm.Page.getAttribute("account").setValue(olookupValue);

No comments:

Post a Comment