CRM 2011 – Javascript and Subgrids code example

Posted on May 19, 2011

28


Someone posted a comment on my blog asking about Javascript and subgrids.  Although I don’t yet need to do anything with Javascript and subgrids I thought I would.  It certainly shows the benefit of Microsoft having forums for CRM problems.

Firstly the question is how to get the values from a subgrid, I found this good forum post and the Javascript is below

You can inspect the subgrid values on save by doing the following:

var gridControl = document.getElementById('subgrid_id').control; 
var ids = gridControl.get_allRecordIds(); 
 for(i = 0; i < ids.length; i++) 

 var cellValue = gridControl.getCellValue('column_name', ids[i]); 
 // logic 
 } 

Doing this on load is a bit more challenging since subgrids are loaded asynchronously and aren’t likely to be done loading when the form onload event fires. You can check the grid periodically though to see when it’s done loading by calling a function like the following in your form onload:

function subGridOnload() 

var grid = document.getElementById('grid_identifications'); 
 if (grid.readyState!="complete") 

 // delay one second and try again. 
 setTimeout(subGridOnload, 1000); 
 return; 

// logic 
}

I then also found a forum post on attaching events to a subgrid, which you can read here

For CRM 2011, your code should look like this:

if (Xrm.Page.ui.getFormType() != 1) {

  Xrm.Page.ui.controls.get("IFRAME_OpportunityLines").setSrc(GetFrameSource("fj_opportunity_new_opportunitymanagementmodu"));;
  Xrm.Page.ui.controls.get("IFRAME_OpportunityLines").onreadystatechange = function oppLineTotals() {
    if (Xrm.Page.ui.controls.get("IFRAME_OpportunityLines").readyState == 'complete') {
      var iFrame = frames[window.event.srcElement.id];
      iFrame.document.all.crmGrid.attachEvent("onrefresh", GridRefresh);
    }
  }
}

Funny thing, the sdk recomended function did not work for me (i.e. Xrm.Page.ui.controls.get(“GridName”) ), and yet the following works (tested!)

var grid = document.getElementById("GridName");
grid.attachEvent("onrefresh", EventHandlerFunction);

because the grid.htc (Html Component) actually includes a public event “onrefresh”… And this event can be handled with any function. We dont need to dive into the eventManager and scriptEvents.

About these ads