Tuesday, 20 April 2010

Writing to a CRM date control from a child form

Despite the fairly innocuous title this issue had been bothering (driving me crazy) for most of the last day.
Problem:
The clients CRM Contact form has a button that uses JavaScript to launch an external web page (we’ll call it the child form). This form would perform a search and return a list of matching users. Each user would have a button and when you clicked a user’s button it would use JavaScript to populate the parent form’s (in this case the CRM contact form) fields such as address, gender, ethnicity and date of birth.

e.g. opener.document.crmForm.all.address1_line1.DataValue = [address text];
Now this worked fine for the text fields, and pick lists but when I tried to write to the date control it did not play nicely. Now to populate a date control in CRM using JavaScript you set the DataValue to a JavaScript date
e.g. opener.document.crmForm.all.birthdate.DataValue = new Date();
However when I called this code from the child form it would populate the CRM Contact Form’s date of birth control successfully but that’s as far as it got. It would then hang if I tried to close or save the form. It would say a CRM error occurred and it that it had to close the form.
However when I tried putting the exact same piece of code without the parent reference in the Contact form’s CRM load event
e.g. crmForm.all.birthdate.DataValue = new Date();
it would work fine. It would save or close the form with no problem. Awesome!! Nothing like inconsistent behaviour.

Solution:
My work colleague Steven Foster wins the chocolate fish for the “magic” workaround (I thought magic sounded better than dirty) that saved the day :)
The solution was to have a hidden text field on the CRM Contact form that the child form would write the date to as text e.g. “21/11/2009”. Fortunately the child form would always write the date in a consistent manner so I could rely on it being in the format “dd/MM/yyyy”. Then I called the hidden fields FireOnChange() event to trigger the CRM OnChanged event. I then added a CRM OnChanged event to the new hidden text field that would parse the string and convert it into a JavaScript date and use that date to populate the date of birth control.

The JavaScript code on the child form
opener.document.crmForm.all.[hidden text field].DataValue = [date of birth text];
opener.document.crmForm.all.[hidden text field].FireOnChange();

The JavaScript on the CRM Contact from hidden text field OnChange event
var textDate = crmForm.all.[hidden text field].DataValue;
var dateParts = textDate.split(“/”);

var birthdate = new Date();
birthdate.setDate(dateParts[0]);
birthdate.setMonth(dateParts[1]-1);
birthdate.setFullYear(dateParts[2]);

crmForm.all.birthdate.DataValue = birthdate;


So there you go problem solved!

No comments:

Post a Comment