CRM 2011 – Javascript to wait for a grid to load and then check for rows

I needed to write some Javascript to check if a subgrid had any values in, if it did have some rows then I expanded the tab and if it didn’t I collapsed the tab

The problem with subgrids is they can take quite a while to appear and then some more time whilst they load the rows and during that time you cannot do anything with them.

I had previously written some  a blog about subgrids but the code wouldn’t work for any more

https://crmbusiness.wordpress.com/2011/05/19/crm-2011-javascript-and-subgrids-code-example/

the line below was always returning null.

var gridControl = document.getElementById('subgrid_id')

So you can see the code below checks to see if the subgrid is null, if so it calls the same function in one second and then does the same until the control is loaded. In the end this code took too long so I did an oData call instead but I thought I would blog it here in case I needed it because it took me a while to work out how to get the subgrid control


function SubGridOnload() {
 ///
 /// waits for the new Claimant expenses grid to load before checking for records.
 ///
 var grid = Xrm.Page.ui.controls.get('CrmGrid')._control;

if (grid.get_innerControl() == null) {
setTimeout(SubGridOnload, 1000);
return;
 }
 else if (grid.get_innerControl()._element.innerText.search("Loading") != -1) {
setTimeout(SubGridOnload, 1000);
return;
 }

var ids = grid.get_innerControl().get_allRecordIds();
 if (ids.length > 0) {
SetDisplay(true);
 } else {
SetDisplay(false);
 }
 }