locked
MS crm 2011 JavaScript to fetch related child entity in parent entity RRS feed

  • Question

  • Hi All,

    I need to do a count of an attribute value from all child records of a parent. I am not sure if this is possible by Javascript.

    I tried fetching value through a retreive request, below is js script:

     In the code new_campaignemail is the entity name, new_regardingcontactid is the relationship lookup created in new_campaignemail entity and new_clicked is the attribute in new_campaignemail.
    Called this JavaScript on load event of Contact the parent entity.
    function Retrieve()
    { 
      var oReq = getXMLHttpRequest(); 
    var g="69148397-94C1-DF11-9A15-ZZXXZXZ";
     if (oReq != null)
      {
        if (g != null)
        {
          oReq.open("GET", Xrm.Page.context.getServerUrl() +"/XRMServices/2011/OrganizationData.svc/new_campaignemailSet?$filter=new_regardingcontactid%20eq%20(guid'" + g + "')&$select=new_clicked", true);
          oReq.onreadystatechange = function () { DisplayData(oReq) };
          oReq.send();
        }
      }
      else
      {
        alert('not supported');
      }
    }
    function getXMLHttpRequest () 
    {
     if (window.XMLHttpRequest)
     {
      return new window.XMLHttpRequest;
     }
     else {
      try  {
     return new ActiveXObject("MSXML2.XMLHTTP.3.0");
     }  catch (ex) {
       return null;  } }}
    function DisplayData (oReq)
    {
     if (oReq.readyState == 4 /* complete */)  
    {
     if (oReq.status == 200)
    { 
          xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.loadXML(oReq.responseText);
          alert("Clicks:" + xmlDoc.selectSingleNode("//d:new_clicked").text);
    
        }  }}

    This does not satisfy the if (oReq.readyState == 4 /* complete */)   condition. I am not sure if this is a corret approach that i am using. 

      Thanks and Regards,

    Naaz






    Friday, April 29, 2011 9:07 AM

Answers

  • var Odata = ODataPath + "/ContactSet?(guid'" + Id + "')";

    this line should be

    var Odata = ODataPath + "/ContactSet(guid'" + Id + "')";

    • Marked as answer by -Naaz Wednesday, May 4, 2011 11:06 AM
    Tuesday, May 3, 2011 11:31 AM
  • hi naaz, glad it is moving forward, I can see only one problem that is

    "/new_campaignemailSet?$filter=

    should change to 

    "/new_campaignemailSet()?$filter=

    • Marked as answer by -Naaz Thursday, May 5, 2011 10:27 AM
    Wednesday, May 4, 2011 1:14 PM

All replies

  • Took some help from SDK , below is some new issue that I faced:

    Below code is from a sample given in sdk. Used just a part of it. Following is what I did:

    1. Added 2 js web resources, json2 and jquery1.5 and called it before calling my web resource on load event of contact

    2. Called below web resource.

    3. Code executes without an error, but the result in alert is "FirstName undefined" and same goes for Contactid

    function init() {
    var ODataPath;
    var startTime; //So that the duration time can be captured.
    var serverUrl;
     serverUrl = Xrm.Page.context.getServerUrl();
     ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
     var Id="803600D7-9607-DF11-8B48-02BF0A064BFE";
     retrieveContactRecord(Id,ODataPath ) 
    }
    
    function retrieveContactRecord(Id,ODataPath ) {
     alert("retrieveContactRecord function START");
     var retrieveReq= new XMLHttpRequest();
    var Odata=ODataPath + "/ContactSet?(guid'" + Id + "')";
     retrieveReq.open("GET", Odata, true);
     retrieveReq.setRequestHeader("Accept", "application/json");
     retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
     retrieveReq.onreadystatechange = function () { retrieveReqCallBack(this); };
     retrieveReq.send();
    }
    
    function retrieveReqCallBack(retrieveReq) {
     if (retrieveReq.readyState == 4 /* complete */) 
    {
     if (retrieveReq.status == 200)
    {
    var retrieved = JSON.parse(retrieveReq.responseText).d;
    alert("FirstName" + retrieved.FirstName );
    alert("ContactId " + retrieved.ContactId );
       }
     else {
      errorHandler(retrieveReq);
      showMessage("retrieveReqCallBack function failure END");
     }
     }
    }
    
    

    Any clue what went wrong because this is basic step what i have tried.

    Thanks and Regards,

    Naaz

    Tuesday, May 3, 2011 8:53 AM
  • var Odata = ODataPath + "/ContactSet?(guid'" + Id + "')";

    this line should be

    var Odata = ODataPath + "/ContactSet(guid'" + Id + "')";

    • Marked as answer by -Naaz Wednesday, May 4, 2011 11:06 AM
    Tuesday, May 3, 2011 11:31 AM
  • Hi Can,

    Thanks for your help it worked.

    I need to go futher and do some more development and have stucked here(below code), Please check if it is correct, Its first time I am using it:

    I need to fetch all new_campaignemail which are related to the current contact. And from new_campaignemail need to get an attribute value and save it in contact.

    In below code new_campaignemail is the entity name,placing filter by relation attribute new_relatedcontactid and passing the contact Id for comparison.

    var Odata=ODataPath + "/new_campaignemailSet?$filter=new_RegardingContactId/Id eq (guid'" + Id+ "')";
    
    

     alert("Value " + retrieved.new_clicked);

     It does not retreives any value and gives the same undefined value.

     

    Thanks and Regards,

    Naaz

    Wednesday, May 4, 2011 11:06 AM
  • hi naaz, glad it is moving forward, I can see only one problem that is

    "/new_campaignemailSet?$filter=

    should change to 

    "/new_campaignemailSet()?$filter=

    • Marked as answer by -Naaz Thursday, May 5, 2011 10:27 AM
    Wednesday, May 4, 2011 1:14 PM
  • Hi Can, Thanks for your response and answer.

    Following is what i did and finally my requirement has met: As discussed earlier I needed child entity records values for some calculations and update the parent record with the value.

    I was using $filter which didn't help in retreiving child records, then tried fetching through relationship name and it got fixed.Uploading code in case it helps anyone. 

    function init() {
    
    var ODataPath;
    
    var serverUrl;
    
    serverUrl = Xrm.Page.context.getServerUrl();
    
    ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
    
    //contactid
    
    var Id= Xrm.Page.data.entity.getId();
    
    retrieveContactRecord(Id,ODataPath ) 
    
    }
    
    
    
    function retrieveContactRecord(Id,ODataPath ) {
    
     var Odata=ODataPath + "/ContactSet(guid'"+Id+"')/new_contact_new_campaignemail";
    
    $.ajax({
    
      type: "GET",
    
      contentType: "application/json; charset=utf-8",
    
      datatype: "json",
    
      url: Odata,
    
      beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
    
      success: function (data, textStatus, XmlHttpRequest) 
    
       { 
    
        RetrieveMultipleEntities(data.d.results,Id,ODataPath );
    
       },
    
      error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + ODataPath ); }
    
     });
    
    }
    
    
    
    function RetrieveMultipleEntities(ManyEntities,Id,ODataPath )
    
    {
    
    var NumberClicked =0 ;
    
     for( i=0; i< ManyEntities.length; i++)
    
     {
    
      var Entity = ManyEntities[i];
    
      var Value = Entity.new_Attribute;
    
    if(Value != "undefined")
    
    {
    
    NumberClicked = Value + NumberClicked ;
    
    }
    
    }
    
     var contact= new Object();
    
     contact.new_Score= NumberClicked ;
    
     UpdateRecords(Id,contact,ODataPath );
    
    }
    
    
    
    function UpdateRecords(Id, contact,ODataPath ) {
    
     if (!Id) {
    
     alert("record id is required.");
    
     return;
    
     }
    
     var jsonEntity = window.JSON.stringify(contact);
    
     var Odata=ODataPath + "/ContactSet(guid'"+Id+"')";
    
     $.ajax({
    
     type: "POST",
    
     contentType: "application/json; charset=utf-8",
    
     datatype: "json",
    
     data: jsonEntity,
    
     url: Odata,
    
     beforeSend: function (XMLHttpRequest) {
    
     XMLHttpRequest.setRequestHeader("Accept", "application/json");
    
     XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
    
     },
    
     success: function (data, textStatus, XmlHttpRequest) { },
    
    error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + ODataPath ); }
    
    });
    
    }
    
    

    Thanks Can Bilgin for your help.

     

    Thanks and Regards,

    Naaz


    Thursday, May 5, 2011 10:26 AM
  • Why I always get nothing using method retrieveContactRecord, any idea maybe important I do wrong?

    the following is the OData:  http://vm-dyndev/CRM/XRMServices/2011/OrganizationData.svc/ContactSet(guid'2B031852-229C-E111-9E08-0023AE7A03EC')/Contact_ActivityPointers

    Thanks!

    Friday, September 21, 2012 2:03 AM