RE: setTimeout being ignored?
Hi,
Please try to add a new intended function into the JS web resource, which will be called when the sub-grid is loaded.
function onGridLoad() {
var functionName = "onGridLoad";
var currentRowCount = null;
try {
//setting timeout beacuse subgrid take some time to load after the form is loaded
setTimeout(function () {
//validating to check if the sub grid is present on the form
if (Xrm.Page != null && Xrm.Page != undefined && Xrm.Page.getControl("Subgrid_2") != null && Xrm.Page.getControl("Subgrid_2") != undefined) {
//stores the row count of subgrid on load event of CRM Form
currentRowCount = Xrm.Page.getControl("Subgrid_2").getGrid().getTotalRecordCount();
if (currentRowCount > _rowCount) {
//call the intended function which we want to call only when records are added to the grid
//alert(111);
//set current row count to the global row count
_rowCount = currentRowCount;
}
else if (currentRowCount < _rowCount) {
//call the intended function which we want to call only when records are removed from the grid
//alert(222);
//set current row count to the global row count
_rowCount = currentRowCount;
}
}
alert(_rowCount);
}, 2000);
} catch (e) {
Xrm.Utility.alertDialog(functionName "Error: " (e.message || e.description));
}
}
And then, adjust your original function as something like the following snippet:
function checkRows(executionContext) {
debugger;
var formContext = executionContext.getFormContext();
var grid = formContext.getControl('Subgrid_2'); //declares subjectivities subgrid as "grid"
if (grid == null) { //if "grid" is empty
setTimeout(function () {
checkRows(executionContext);
grid.addOnLoad(onGridLoad);
}, 5000); //if the grid hasn’t loaded in time it runs this again when it has
return;
}
var filteredRecordCount = grid.getGrid().getTotalRecordCount(); //Count records
alert(filteredRecordCount)
if (filteredRecordCount == 0) { //if none then...
formContext.getControl('statuscode').removeOption(283390001); //Hide "Approved with Subjectivities" value
}
}
Since I can't know exactly which entity you're triggering this JS on, you'll need to adapt your code to the actual use.
Make sure that:
- addOnLoad function has been called in the original function.
- There is a delay between the two TimeOuts.
Here, for example, I alerted the count of the child contacts for an account when its form is refreshed. The count can be alerted after the sub-grid Contacts is loaded.