Saturday, July 23, 2011

Retrieve multiple records from an entity using JavaScript in MS CRM 4.0

Here is a JavaScript method which can be used to retrieve multiple records from an entity using CRM Web Service. This method can be used to retrieve data from any CRM entity. It requires following parameters to be passed:
1.       entityName: Then schema name of an entity to be retrieved.
2.       arrColumnName: Array of attributes to be retrieved.
3.       enableDistinct: Boolean value to get distinct records form an entity.
function RetrieveMultiple(entityName, arrColumnName, enableDistinct)
{
   
    if((entityName != null) && (entityName.length > 0) && (arrColumnName != null) && (arrColumnName.length > 0))
    {
       
        var ColumnsSetAttributes = '';
        var IsDisinctValue = false;
       
        // Build columns to be retrieved
        for(var i = 0; i < arrColumnName.length; i++)
        {
            ColumnsSetAttributes += " <q1:Attribute>" + arrColumnName[i] + "</q1:Attribute>"
        }
       
        //Set Distinct value
        if(enableDistinct != null && typeof(enableDistinct) != "undefined" && (enableDistinct.toLowerCase() == "true" || enableDistinct == true))
        {
            IsDistinctValue = true;
        }
       
        var xml = "<?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>" +
         " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
         " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
         " <q1:EntityName>" + entityName + "</q1:EntityName>" +
         " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
         " <q1:Attributes>" +
         ColumnsSetAttributes +
         " </q1:Attributes>" +
         " </q1:ColumnSet>" +
         " <q1:Distinct>" + IsDistinctValue + "</q1:Distinct>" +
         " </query>" +
         " </RetrieveMultiple>" +
         " </soap:Body>" +
         "</soap:Envelope>";

         var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
         xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
         xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
         xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
         xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
         var oXml;
        
         try
         {
             xmlHttpRequest.send(xml);
             oXml = xmlHttpRequest.responseXML;
            
             // Check for errors.
             if(oXml != null)
             {
                var errorCount = oXml.selectNodes('//error').length;
                if (errorCount != 0)
                {
                   var msg = oXml.selectSingleNode('//description').nodeTypedValue;              
                   alert(msg);                  
                }
                else
                {
                   //return the Business Entity node
                   return oXml.selectNodes("//BusinessEntity");
                }
            }
            else
            {
                alert("Error: No response received.");               
            }
        }
        catch(e)
        {  
            if(oXml != null)
            {
                var err = oXml.getElementsByTagName("description")[0].childNodes[0].nodeValue; 
                alert("Error: " + e.description + ": " + err);              
            }
            else
            {
                alert("Error: Unexpected error occurred.");
            }           
        }
   
    }  
    return null;
}

Example:
To retrieve primary key and name from contact entity create an array for attributes to be retrieved and pass contact entity schema name as follow:
//Example: To retrieve primary key and name from contact entity
var EntityName = "contact";
var AttributeList = new Array();
AttributeList[0] =  "contactid";
AttributeList[1] =  "name";

var responseXml = RetrieveMultiple(EntityName,AttributeList, false);

if(responseXml != null)
{
    for(i = 0; i < responseXml.length; i++)
    {
        var ContactId = responseXml[i].childNodes[0].text;
        var ContactName = responseXml[i].childNodes[1].text;
    }
}

No comments:

Post a Comment