Wednesday, April 13, 2011

Retrieve using ODATA and JSON in CRM 2011

In this example i am trying to retrieve Account entity information in  form load script using ODATA  and JSON in CRM 2011

To use ODATA service 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

function init()
{
// write required ODATA query
var odataSelect = "http://server/orgname/XRMServices/2011/OrganizationData.svc/AccountSet(guid'6C2EFF37-BD39-E011-91D1-000C2971AF13')";

$.ajax({
       type: "GET",
       contentType: "application/json; charset=utf-8",
       datatype: "json",
       url: odataSelect,
       beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
       success: function (data, textStatus, XmlHttpRequest) 
           { 
               
                
// Use this method for a selection that  return single entitie
               RetrieveEntityData(data.d);

             
              // Use this method for a selection that may return multiple entities
               RetrieveMultipleEntities(data.d.results);
           
           },
       error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
   });
}



function RetrieveEntityData(Entity)
{  
    // get the fields from the Entity object
     var accountNumber = Entity.AccountNumber;
     var AccountName = Entity.Name;
    
alert(Entity.Name);   
}


function RetrieveMultipleEntities(ManyEntities)
{


  for( i=0; i< ManyEntities.length; i++)
  {
// get the fields from the Entity object
     var Entity = ManyEntities[i];
     var accountNumberAttribute = Entity.AccountId;    
     var AccountName = Entity.Name;
     
alert(Entity.Name);   
  }
}


Just call the init 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