I have successfully created a JavaScript OnSave event that scans a grid of a "Sales Quota Distribution" entity on an "Opportunity" entity form, looking for duplicates in the "Resource" field. When a duplicate is found, a warning message is displayed. Everything is functioning as expected, but I am now trying to enhance the OnSave event to prevent the user from saving the form if there are no duplicate resources. How can I achieve this?
Here is the current code snippet:
function GetTotalResourceCount(executionContext) {
console.log("function started");
var execContext = executionContext;
var formContext = executionContext.getFormContext();
var resourceyescount = 0;
try {
var gridCtx = formContext._gridControl;
var grid = gridCtx.getGrid();
var allRows = grid.getRows();
//get rows - use the getControl method and pass the grid name.
//var gridContext = formContext.getControl("s_qd");
// if (formContext.getGrid().getTotalRecordCount() == 0) {
// setTimeout(function () { GetTotalResourceCount(execContext); }, 2000);
// return;
// }
var duplicatesFound = 0;
//loop through rows and get the attribute collection
allRows.forEach(function (row, rowIndex) {
var thisRow = row.getData().entity;
var thisRowId = thisRow.getId();
var thisResource = "";
var thisResourceName = "";
var thisResourceID = "";
console.log("this row id=" + thisRowId);
var thisAttributeColl = row.getData().entity.attributes;
thisAttributeColl.forEach(function (thisAttribute, attrIndex) {
var msg = "";
if (thisAttribute.getName() == "new_resource") {
thisResource = thisAttribute.getValue();
thisResourceID = thisResource[0].id;
thisResourceName = thisResource[0].name;
}
});
// Loop through every row and find one with
// thatresource == thisResource &&
// thatrow ID != thisRowId
var allRows2 = formContext.getGrid().getRows();
//loop through rows and get the attribute collection
allRows2.forEach(function (row, rowIndex) {
var thatRow = row.getData().entity;
var thatRowId = thatRow.getId();
var thatAttributeColl = row.getData().entity.attributes;
var thatResource = "";
var thatResourceName = "";
var thatResourceID = "";
thatAttributeColl.forEach(function (thatAttribute, attrIndex) {
if (thatAttribute.getName() == "new_resource") {
thatResource = thatAttribute.getValue();
thatResourceID = thatResource[0].id;
thatResourceName = thatResource[0].name;
if (thatResourceID == thisResourceID && thatRowId != thisRowId) {
duplicatesFound++;
var msg = "Duplicate resource " + thatResource;
}
}
});
});
});
if (duplicatesFound > 0) {
console.log("duplicate found");
Xrm.Utility.alertDialog("WARNING: There are duplicate resources in the Sales Quota Distribution grid.");
}
} catch (err) {
console.log('Error occurred :' + err)
}
}
Any assistance on how to achieve this additional functionality would be highly appreciated. Thank you! https://i.sstatic.net/A1U4q.png