use of XML query to fetch data in CRM forms

Posted on Posted in MS Dynamics, MS Dynamics CRM

How to fetch data in CRM 4 using JavaScript in web forms
Let’s say we want to verify if a customer is eligible to buy a ticket
First thing we need to create is a XML query
In query below we will get data back for two attributes on the basis of two/multiple criteria and order by descending of an attribute
var check2 = “secondcheck”;

crmForm.isPcdContractAllowed = function ( ) {
var check1 =”ABC1″;

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>MyEntityName</q1:EntityName>” +
” <q1:ColumnSet xsi:type=\”q1:ColumnSet\”>” +
” <q1:Attributes>” +
” <q1:Attribute>columnA</q1:Attribute>” +
” <q1:Attribute>columnB</q1:Attribute>” +
” </q1:Attributes>” +
” </q1:ColumnSet>” +
” <q1:Distinct>false</q1:Distinct>” +
” <q1:Criteria>” +
” <q1:FilterOperator>And</q1:FilterOperator>” +
” <q1:Conditions>” +
” <q1:Condition>” +
” <q1:AttributeName>columnC</q1:AttributeName>” +
” <q1:Operator>Equal</q1:Operator>” +
” <q1:Values>” +
” <q1:Value xsi:type=\”xsd:string\”>” + check1 + “</q1:Value>” +
” </q1:Values>” +
” </q1:Condition>”;
if (check2)
{
xml += ” <q1:Condition>” +
” <q1:AttributeName>columnD</q1:AttributeName>” +
” <q1:Operator>NotEqual</q1:Operator>” +
” <q1:Values>” +
” <q1:Value xsi:type=\”xsd:string\”>” + check2 + “</q1:Value>” +
” </q1:Values>” +
” </q1:Condition>”;
}
xml += ” </q1:Conditions>” +
” </q1:Criteria>” +
” <q1:Orders>” +
” <q1:Order>” +
” <q1:AttributeName>columnA</q1:AttributeName>” +
” <q1:OrderType>Descending</q1:OrderType>” +
” </q1:Order>” +
” </q1:Orders>” +
” </query>” +
” </RetrieveMultiple>” +
” </soap:Body>” +
“</soap:Envelope>” +
“”;

// make Web Service call
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);
xmlHttpRequest.send(xml);

// catch return from Web Service
var resultXml = xmlHttpRequest.responseXML;

var entityNodes = resultXml.selectNodes(“//RetrieveMultipleResult/BusinessEntities/BusinessEntity”);
var result;

for (var i = 0; i < entityNodes.length; i++) {
var entityNode = entityNodes[i];

var columnANode = entityNode.selectSingleNode(“q1:columnA”);
var columnA = (columnANode == null) ? null : columnANode.text;
}
}