Wednesday, February 23, 2011

using ODATA to retrieve data from a custom Entity in CRM2011

In this example i am going to retrieve related custom entity attributes information in a CRM form load script using ODATA feature of CRM2011


To use ODATA you need two resource files
  JSON and JQuery




you can download these popular resource in web...
Now write following java script in the new web resource file


var ODataPath;
var serverUrl;


// here lid is the parameter that we will be passing while calling this method in crm form
function getCity(lid) {
    // Set Global Variables

    var context = Xrm.Page.context;
    serverUrl = context.getServerUrl();
    ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
    startTime = new Date();
     var locid = lid[0].id;
// here i'm passing lookup guid as parameter to retrieve that lookup entity related information   
 retrieveCity(locid );


}


function retrieveCity(Id) {



 var retrieveCityReq = new XMLHttpRequest();


// here is the entityset value you can get from the ODATA organization service
 retrieveCityReq.open("GET", ODataPath + "/new_entitySet(guid'" + Id + "')", true);
 retrieveCityReq.setRequestHeader("Accept", "application/json");
 retrieveCityReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
 retrieveCityReq.onreadystatechange = function () {
  retrieveCityReqCallBack(this);
 };
 retrieveCityReq.send();


}


function retrieveCityReqCallBack(retrieveCityReq ) {
 if (retrieveCityReq.readyState == 4 /* complete */) {
  if (retrieveCityReq.status == 200) {
   //Success
   var retrievedCity = JSON.parse(retrieveCityReq.responseText).d;
// here i'm retrieving pick list data
  alert("Retrieved City = " + retrievedCity.new_City.Value+ "");
  
// Assigning retrieved pick list  value to form element
Xrm.Page.getAttribute("new_city").setValue(retrievedCity.new_city.Value); 


     }
  else {
   //Failure
   errorHandler(retrieveBrandtReq);
  alert("retrieve Brand ReqCallBack function failure ");
  }
 }
}


Just call the getCity method from the CRM form events, but make sure you have to add JSON and JQuery web resources to the event library before adding this web resource. It has to follow the sequence JSON,JQuery and Custom web Resource.




To get the Required entity ODATA set use the following url
http://server/XRMServices/2011/OrganizationData.svc/new_enitityset





"The only reward of virtue is virtue; the only way to have a friend is to be one."
- Ralph Waldo Emerson


No comments:

Post a Comment