Monday, March 5, 2012

CRM 2011 Retrieve Records using REST Endpoints



REST Endpoints and jQuery is one of the good way to retreive record(s) from CRM 2011.

Step1 : You  have to use the following jQuery files in to to your solution. they are

1. jquery-1.6.2.min.js (or use the latest version(recommended))
2. json2.js


Now..

Step2:
in  CRM 2011 SDK we can see several good example. we will make use of them to set the lookup field on a custom entity.

// Set lookup value of a field
function setLookup(fieldName, id, name, entityType) {
if (fieldName != null) {
   var olookupValue = new Array();
   olookupValue[0] = new Object();
   olookupValue[0].id = id;
   olookupValue[0].name = name;
   olookupValue[0].entityType = entityType;
   Xrm.Page.getAttribute(fieldName).setValue(olookupValue);
}
}


function retrieveContactId() {
if (Xrm.Page.ui.getFormType() == 1) {
  // Get the CRM URL
  var serverUrl = Xrm.Page.context.getServerUrl();


 // Cater for URL differences between on premise and online  if (serverUrl.match(/\/$/)) {
  serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}

// Specify the ODATA end point (this is the same for all CRM 2011 implementations)
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
// Specify the ODATA entity collection (this needs to be specific to your entity)
var ODATA_EntityCollection = "/ContactSet";


// Specify the ODATA filter
var ODATA_Query = "?$select=ContactId&$filter=FullName%20eq%20\'new%20contact\'&$top=1";


// Build the URL
var ODATA_Final_url = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + ODATA_Query;


//Calls the REST endpoint
$.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    url: ODATA_Final_url,
    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) {
 

//This function will trigger asynchronously if the Retrieve was successful
  setLookup("new_contact", data.d.results[0].ContactId, "new contact", "contact");
},


error: function (XmlHttpRequest, textStatus, errorThrown) {

//This function will trigger asynchronously if the Retrieve returned an error
alert("My ajax call failed....");
}
});
}
}
By calling the retrieveContactId function on ur script, it will automatically load the lookup filed on the form.
on the setLookup function you have to pass the lookup filed name that you want to fill the data.



Hope this helps to someone !

Cheers!
Safi.
  


         
           
       
   

No comments:

Post a Comment