javascriptdynamics-crmdynamics-crm-4

Retrieving an entity's attributes by GUID


I have a form that contains a lookup to a contact. Therefore I can get the guid, name and typename of the contact.

This code:

var temp =  crmForm.all.to.DataValue;
alert(temp[0].id + "\n" + temp[0].name + "\n" + temp[0].typename); 

returns a valid guid, name, and type.

How can I get the attributes of this contact (the phone numbers in this case) with this information? I am trying to do this in the OnLoad function of a form, so I need to do this in javascript.


Solution

  • You can use the following method to call the webservices

    function GetObjectAttribute(objectid, entityname, attribute) {
        // Preparer the SOAP message
        var message =
            [
            "<?xml version='1.0' encoding='utf-8'?>",
            "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'",
            " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'",
            " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>",
            GenerateAuthenticationHeader(),
            "<soap:Body>",
            "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>",
            "<entityName>",
            entityname,
            "</entityName>",
            "<id>",
            objectid,
            "</id>",
            "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query'",
            " xsi:type='q1:ColumnSet'>",
            "<q1:Attributes><q1:Attribute>",
            attribute,
            "</q1:Attribute></q1:Attributes>",
            "</columnSet></Retrieve>",
            "</soap:Body></soap:Envelope>"
            ].join("");
    
        var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        xmlhttp.open("POST", "/MSCrmServices/2007/CrmService.asmx", false);
        xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
        xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        xmlhttp.setRequestHeader("Content-Length", message.length);
        xmlhttp.send(message);
    
        var result = xmlhttp.responseXML;
        var error = result.selectNodes('//error').length;
        if (error == 0) {
            var attributeNode = result.selectSingleNode('//q1:' + attribute);
            if (attributeNode != null) {
                return attributeNode.text;
            }
        }
        return null;
    }
    

    usage

    var fullname = GetObjectAttribute(<GUID>, "Contacts", "fullname");