Instant Math in the Grid
When a user changes the Quantity or Unit Price in an editable Interactive Grid, they expect the Line Total to update immediately without a page submission. Client-side row-level calculations provide this instant feedback using the IG model API and Dynamic Actions.
Dynamic Action Approach
Create a Dynamic Action on the IG’s Column Change event. In the Client-side Condition, check that the changed column is one of the inputs (QUANTITY or UNIT_PRICE). In the True action, use JavaScript to compute and set the result:
// Dynamic Action: Event = Column Change [myGrid]
// Client-side Condition: Column = QUANTITY or UNIT_PRICE
// True Action: Execute JavaScript Code
var grid = apex.region("myGrid").widget().interactiveGrid("getViews","grid");
var model = grid.model;
var selectedRecords = grid.getSelectedRecords();
if (selectedRecords.length > 0) {
var record = selectedRecords[0];
var qty = parseFloat(model.getValue(record, "QUANTITY")) || 0;
var price = parseFloat(model.getValue(record, "UNIT_PRICE")) || 0;
var discount = parseFloat(model.getValue(record, "DISCOUNT_PCT")) || 0;
var lineTotal = qty * price * (1 - discount / 100);
model.setValue(record, "LINE_TOTAL", lineTotal.toFixed(2));
}
Updating a Page Item With Grid Totals
To show the grand total of all rows in a page item outside the grid, iterate over all records after any cell change:
// After setting the row value, recalculate grand total
var grandTotal = 0;
model.forEach(function(record) {
var lineTotal = parseFloat(model.getValue(record, "LINE_TOTAL")) || 0;
grandTotal += lineTotal;
});
apex.item("P10_GRAND_TOTAL").setValue(grandTotal.toFixed(2));
Making the Calculated Column Read-Only
The LINE_TOTAL column should be editable in the model (so JavaScript can set its value) but not directly editable by the user. Set the column’s Type to “Display Only” in the IG column attributes but ensure it is still included in the model by keeping it in the SQL query. Alternatively, keep it as a text field but use the column’s “Read Only” condition to prevent user input.
Handling New Rows
When the user adds a new row, the calculation should also fire. Listen for the model’s “addRecordEnd” event in the IG initialization code to attach the calculation logic to newly created rows. Alternatively, set default values for QUANTITY and UNIT_PRICE so the LINE_TOTAL computes to a sensible default immediately.
Server-Side Validation
Client-side calculations provide instant feedback but can be bypassed. Always recalculate on the server in the DML process or a validation to ensure data integrity. The client calculation is for UX; the server calculation is for data correctness.