Tuesday 14 June 2011

CRM 2011: Get parent window attribute data, when opening from grid view.


Good day, fine people of the Internet.

A request was handed to me in my day to day work, which required some custom JavaScript work. Essentially, the requirement was for an onLoad event attached to a custom entity, this event must query the parent entity it was opened from, and depending on the result returned, sets the values of various fields on the form.

My custom entity has a relationship of N:1 with contact, however depending on the contact type (customer, supplier etc.) my custom entity will behave differently.

Through various research methods (Google) it seems the standard way to query an attribute on a parent window is to use..

window.parent.opener.Xrm.Page.getAttribute("Attribute_Name")
And to get the attribute’s value / data
window.parent.opener.Xrm.Page.getAttribute("Attribute_Name").getValue();

Great, Job done!!… errr…Not quite.

This scenario is ONLY suitable, when creating my new entity record from the navigation bar link, and hitting new.

For my scenario, I have a grid view on the contact entity, which lists the custom entity records. From here, I can click the grid, and add new record via the ribbon.
lo and behold, my page threw a tantrum along with an error.

After some debugging and a few moments rocking in the corner, I discovered the problem/solution

The problem:
window.parent.opener.Xrm.Page.getAttribute("Attribute_Name") Will not work when launching the entity from a grid view, because you cannot call the getAttribute method! ... WHY?
Because this a "short-cut" to the method used in standard form control, which does not exist when you open a record from a grid.

The solution:
Use this…

window.parent.opener.Xrm.Page.data.entity.attributes.get("Attribute_Name");
And to get the attribute’s value / data
window.parent.opener.Xrm.Page.data.entity.attributes.get("Attribute_Name").getValue();   

NOTE:
If you have a scenario where your record can be opened from both a grid AND the navigation area, this new method will not work for both, It’s only for grid launches.

My overall solution is to use both methods in my events, with a try/catch surrounding them.
Then, my remaining logic begins on whichever is successful.

Hope this helps you..
Craig Hamer

3 comments:

  1. Thank you very much..you saved my day..!!
    somtimes small things like this can knock you day off..

    ReplyDelete
    Replies
    1. You're very welcome, I'm glad it helped you :)

      Delete
  2. Thank you so much. Your code work like charm...

    ReplyDelete

Thanks for your comment

Craig Hamer