vrijdag 3 april 2009

Count related items (javascript)

Jim Wang has recently
posted
an article to view the totals of activities and hisoty items.


This article was really very usefull to implement for other related entities.
So I hacked into the code and made sure these counts are done asynchronously.

When items are count, the users sees the "loading" icon while waiting for the result.


CountRelatedItems = function(entityName, filterAttribute, filterValue, navObject) {
if (navObject != null) {

var originalImage = null;

//set loading image
if (navObject.childNodes != null && navObject.childNodes[0] != null) {
originalImage = navObject.childNodes[0].src;
navObject.childNodes[0].src = '/_imgs/btn_lookup_resolving.gif';
}

var xml = "" +
"" +
"" + GenerateAuthenticationHeader() +
" " +
" " +
" ";
xml += " " + entityName + "";
xml += " " +
" " +
" statuscode" +
"
" +
"
" +
" false" +
" " +
" And" +
" " +
" " +
" statuscode" +
" Equal" +
" " +
" 1" +
"
" +
"
" +
" ";
xml += " " + filterAttribute + "";
xml += " Equal" +
" " +
" " + filterValue + "" +
"
" +
"
" +
"
" +
"
" +
"
" +
"
" +
"
" +
"
" +
"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", true);
xmlHttpRequest.onreadystatechange = function() {
if (xmlHttpRequest.readyState == 4) {
var buNodes = xmlHttpRequest.responseXML.selectNodes("//BusinessEntity/q1:statuscode"); // CRM 4.0
if (navObject != null) {
navObject.getElementsByTagName('NOBR')[0].innerText =
navObject.getElementsByTagName('NOBR')[0].innerText + " (" + buNodes.length + ")";
//set original image
if (navObject.childNodes != null && navObject.childNodes[0] != null)
navObject.childNodes[0].src = originalImage;
}

}
}
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);
}
}


To call this function, for example to count the number of related contacts to an account, the following syntax can be used:

CountRelatedItems("contact", "parentaccountid", crmForm.ObjectId,
document.getElementById('navContacts'));