Pages

Tuesday, January 15, 2013

Access Main form fields from Nav Area via Jscript

Let's say you need to access form fields via jscript when you have navigated to one of the navigational links on the entity. For example, when the account form is open but you are currently on the "More Addresses" navigation.


A typical scenario for such a requirement is if you have configured a custom button on the sub-grid ribbon that links to a jscript function where you need to pass through some parameters that are set from fields on the main form.

If you try and access the fields using the standard Xrm.Page approach while in the above navigational scenario, your jscript will error out. Like so:

function CustomAction() {

 var parameters = {};
 parameters["snt_customid"] = Xrm.Page.data.entity.getId();
    parameters["snt_customidname"] = Xrm.Page.data.entity.attributes.get("snt_name").getValue();
 
 Xrm.Utility.openEntityForm("snt_custom", null, parameters);

}

The solution is pretty much the same as how page elements are referenced from html web resources linked to a form i.e. using the prefix of "window.parent". Therefore updating the function as follows should do the trick:

function CustomAction() {

 var parameters = {};
 parameters["snt_customid"] = window.parent.Xrm.Page.data.entity.getId();
    parameters["snt_customidname"] = window.parent.Xrm.Page.data.entity.attributes.get("snt_name").getValue();
 
 Xrm.Utility.openEntityForm("snt_custom", null, parameters);

}

Update:

The above design has one flaw and that is if you decide to use a sub-grid to bring in the navigation link into the main body of the form. When you do so, the same sub-grid menu shows up when you click on the sub-grid but there is one essential difference...



In the case of the former, the main form is no longer in view and therefore you cannot access the form elements (Xrm.Page.data) without using the "window.parent" prefix. I you don't use this prefix you will receive a jscript errror.

In the case of the latter the main form is still in view and therefore Xrm.Page.data is accessible. And therefore if you use the "window.parent" prefix you will receive a jscript error.

In order to cater for both scenarios the solution is quite simple - simply use the try/catch exception handling feature. This way if an exception occurs it will go to the alternate access method which will then succeed.

function CustomAction() {

 var parameters = {};
 var id;
 var name;
 try {
  // if called from Nav Link navigation
  id = window.parent.Xrm.Page.data.entity.getId();
  name = window.parent.Xrm.Page.data.entity.attributes.get("snt_name").getValue();
 } catch (e) {
  // if called from Embedded Grid navigation
  id = Xrm.Page.data.entity.getId();
  name = Xrm.Page.data.entity.attributes.get("snt_name").getValue();
 }
 parameters["snt_customid"] = id;
 parameters["snt_customidname"] = name;

 Xrm.Utility.openEntityForm("snt_custom", null, parameters);
}

No comments:

Post a Comment