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);
 }
 }

6 thoughts on “CRM 2011 – Javascript to wait for a grid to load and then check for rows

  1. Vogelgesang Consulting February 27, 2014 / 9:12 am

    Do you have the same for CRM 2013?

    Like

    • Hosk February 27, 2014 / 9:20 am

      The code might work for CRM 2013, have you tried it?

      Like

  2. Syed Hussain February 27, 2014 / 2:05 pm

    I’ve played about with things like this in the past but the code above I have found to be unpredictable. The best way is to do this is to do a Fetch aggregate count; if the count is higher than zero expand the Tab. Or, you could create a ASYNC plugin that updates a field on the form – the tab is then expanded based on the value in that field.

    I generally hate attaching code to the onLoad and onsave event handlers – it ties up the form and messes with the user experience. It might work well in testing, but in a production environment when several forms are open and the same time it really does make a massive difference.

    Like

  3. Mohamed May 14, 2015 / 10:32 pm

    How would this work if the grid has no rows? Would it loop forever?

    Like

    • Hosk May 14, 2015 / 10:46 pm

      good question, I’m not sure now but I don’t recall it looping forever at the time

      Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.