Thursday, March 11, 2010

JavaScript code to pre populate fields on associated record opened from parent or related record

Recently, I came across a scenario, where it was required that some fields be pre-populated on a new form opened from associated view of a record.
One possible solution is to fire a SOAP Xml retrieve request to get the desired fields of the related record and set them on the new form. But this approach requires a database interaction using MS CRM web services, that can cause a noticeable delay in form load.
An alternative to this approach is to access parent record using JavaScript object model and access the fields on form to set values on new form.
Following sample code can be added to OnLoad event of form to achieve the same:

//*****************************************************************************
//Functionality- In create mode, get default values from associated location record
//*****************************************************************************
if (crmForm.FormType == 1) {

//If form is being opened using an existing parent record
if ((window.opener != null) && (window.opener.parent != null) && (window.opener.parent.document != null) && (window.opener.parent.document.crmForm != null)) {
var oParentCrmForm = window.opener.parent.document.crmForm;
if (oParentCrmForm == null oParentCrmForm == undefined) {
}
else {
if (oParentCrmForm.ObjectTypeName == 'parent') {
//Set field value as on parent
crmForm.all.field1.DataValue = oParentCrmForm.all.field1.DataValue;
}
}
}
}
//*****************************************************************************

Data fetched using this approach is the current data on the form that may not be saved to the database yet.

Hope this helps.

No comments:

Post a Comment