Get Field Data from Related Entity Using Javascript

15 Aug

The following javascript code can be added to lookups in order to get more data from related records.

So lets create a function that takes the lookup value and then queries the CRM. In this example below we have a lookup to a project record from an entity called Timeslips.

function GetProjectInfo() {

   //Getting the Lookup object from the CRM Page
   var ProjectObject = Xrm.Page.getAttribute("abil_projectid").getValue();

   // Getting the GUID for the Project record
   var ProjectNoID= ProjectObject[0].id;

   //Stripping out the curly brackets
   ProjectNoID = ProjectNoID.replace('{', '').replace('}', '');

   //Checking if we have a project GUID Value
   if (ProjectNoID != null) {

      //Let’s create the Web Service URL
      oDataPath = Xrm.Page.context.getServerUrl() + "/xrmservices/2011/organizationdata.svc";

      //Call the project retrieve function
      RetrieveProjectRecord(ProjectNoID, oDataPath);

This piece of code is relatively straight forward. Now we need to create the retriever function in order to get our data back. Here is the retriever code below.

function RetrieveProjectRecord(Id, ODataPath) {

   var retrieveReq = new XMLHttpRequest();"GET", ODataPath + "/abil_projectSet(guid'" + Id + "')", true);
   retrieveReq.setRequestHeader("Accept", "application/json");
   retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");

   retrieveReq.onreadystatechange = function () {

This function handles the calling of the web service and retrieving of the data. As you can see ‘abil_projectSet’ is added to the URL to call the OData REST webservice to obtain the relevant record from the abil_project entity.

The final function is called retrieveProjectReqCallBack and is used to parse the JSON data handed back. Here we are taking the retrived data and inserting it into the forms fields.

function retrieveProjectReqCallBack(retrieveProjectReq) {
   if (retrieveProjectReq.status == 200) {
      var retrievedProject = JSON.parse(retrieveProjectReq.responseText).d;
      var ProjectName = retrievedProject.abil_ProjectName;
   } else {
      alert("Error in Fetching data");

Once these have been created as a single web resource then the GetProjectInfo function can be added to the lookup field.

For instruction how to do this go to here

Any questions or feedback is always appreciated.

Leave a Reply