Thursday, 8 May 2008

crmForm.SetFieldReqLevel throws error when label got renamed

Hi All,

I came accross an interesting little problem today that took me a while to figure out. This happens in CRM4, but I am fairly sure the same will happen in CRM3.

I have a lookup field to contact called nzi_clientid with a label of Client, I want to rename it to Contact under certain conditions but leave it as Client under other other conditions.

To rename a field on a form has been documented online as:
crmForm.all.nzi_clientid_c.innerText = "Client";

The problem is that if you rename the field using this method, the well documented way to make a field required (crmForm.SetFieldReqLevel("nzi_clientid", 1)) does not work, and it throws an error, "Object doesn't support this property or method".

I had to delve into the html to see what was happening. It turns out that using the above method to rename the field label overwrites more than the label. Before the rename the innerHTML looks like this:

The rename replaces this entire xml section with the new name e.g. "Contact". We don't want this because the crmForm.SetFieldReqLevel cannot find the field any longer because the LABEL node has been overwritten and replaced with "Contact".

<TD class=" ms-crm-Field-Normal" id="nzi_clientid_c" title="Client" style="DISPLAY: inline">

Two ways to fix this is to either to a text replace of the word "Client" in the innerHTML and replace it with "Contact", but this is more than the one or two lines and makes it too complicated.

Second way is to overwrite the firstChild with the new label "Contact". This will mean that the original LABEL node still exists, but the img that shows whether the field is required or not, is gone, even though the field is technically still required. Since I analyse the field right after this and set whether it is required or not, this is not an issue for me.

crmForm.all.nzi_clientid_c.firstChild.innerText = "Client";
if (isRequired)
crmForm.SetFieldReqLevel("nzi_clientid", 1)
crmForm.SetFieldReqLevel("nzi_clientid", 0)