Pages

Monday, September 12, 2011

DOM Events and CRM 2011

[UPDATED: 2013.04.11 I've learned a lot since this premature post, and have struck out all the incorrect information.]

Recently, another MVP asked in a private forum how one might connect to the “onclick” event of a CRM field.  With the new Xrm.Page namespace object model, it seemed that all references to the actual DOM element of the control were lost (or at least, very well hidden).  Well, I did some poking around, and I discovered two one things:
  1. Xrm.Page lives only within the scope of web-resources and their execution (wherever and however they are scripted to occur); this means that the old days of firing up the IE Developer Toolbar to hack CRM on-the-fly are gone.
  2. The DOM elements are buried in undocumented members of the control object (as opposed to the attribute object).  As a consequence, the following hack is unsupported, but also much easier to implement than the supported method of using a Web Resource to present your own custom controls that drive, in the background, CRM’s native controls.
So, here’s the method I found to achieve access to the DOM element control container, and how to assign a new “onclick” handler to it:
var controlname = "ownerid"; // The "Owner" field, as an example

function myFunction ()
{
alert("I have been clicked");
}

Xrm.Page.getControl(controlName)[“_control”][“_element”].attachEvent(‘onclick’, myFunction);

Wasn’t that easy?