Jul 22, 2011

Issue of reading parent entity from create form in CRM 2011

In CRM 2011, reading the parent fields from child form has a trick. For example, if you are reading a quote field while you are in quote product should be done carefully. Usually, it’s advised to do as follows;

var pageParent = window.top.opener.parent.Xrm.Page;
var preantName = pageParent.getAttribute("Name").getValue();

This doesn’t work for create forms, but Update forms! So you are required to do something like this to read from Create forms..

var preantName = window.parent.opener.crmForm.all.name.DataValue;

When I come across this, I simply wrote below method which worked for me. This handles both Create and Update form types for you. May be this can’t be the best code, but I couldn’t find a better code in the web.

function ReturnParentField(_fieldName)
{
 var FORM_TYPE_CREATE = 1;
 var FORM_TYPE_UPDATE = 2;
  
 var formType = Xrm.Page.ui.getFormType();
 var _pageParent = window.top.opener.parent.Xrm.Page;
 var _value = null;

 if (formType==FORM_TYPE_CREATE)
 {
   if (eval('window.parent.opener.crmForm.all.'+_fieldName+'.DataValue') != null)
   {
    _value = eval('window.parent.opener.crmForm.all.'+_fieldName+'.DataValue');
   }
  }
  else if (_pageParent != null)
  {
    if (_pageParent.data != null)
    {
       if (eval('_pageParent.getAttribute("'+_fieldName+'").getValue()') != null)
       {
           _value = eval('_pageParent.getAttribute("'+_fieldName+'").getValue()');
       }
     }
     else
     {
       _value = eval('window.parent.opener.crmForm.all.'+_fieldName+'.DataValue');
     }
   }
   return _value;
}

When you go through this code, you will see some complexity in the later stage when I have made it handle two ways for update form. That’s because, when you access existing record from usual associate view (_pageParent.data != null) and its possible to use getAttribute() method accordingly. In CRM 2011 contains new feature of accessing the associate records (or child records) within the form area called sub-grids which doesn’t work like this. It contained no attributes to read. Luckily, it again enables you to read parent information in most traditional way, which we have used in Create form type.

Hope this will help.

No comments:

Post a Comment