Auto-Calculate Totals and Derived Fields¶
An accounts payable indexer types quantity, unit price and tax rate from an invoice line. The subtotal, tax and grand total should fill in as they type, so nobody does the arithmetic by hand and the stored totals always match the inputs. The same pattern builds any field from others, for example a full name from first and last name.
At a glance
- Extension point Custom Index Behavior
- You need Input fields
Quantity,UnitPrice,TaxRate(Textbox, Currency or NumericUpDown) and output fieldsSubtotal,TaxAmount,GrandTotal(Textbox or Currency); permission to edit content types in the Connections app - Teaches One script on several trigger fields, reading numbers stored as strings, writing strings with behaviors suppressed
Set it up¶
- In the Connections app, open the invoice content type.
- Select
Quantity. Open Behaviors > Add a Behavior > Custom Behavior. Name itCalculate totals, paste the script below, and select Save & Close. - Add the same script to
UnitPriceand toTaxRate. A behavior runs only when its own field changes, so every input needs a copy. - Make
Subtotal,TaxAmountandGrandTotalread-only on the content type, so users do not overwrite them.
TaxRate is a percentage, for example 8.25.
Script¶
// Attach to: Quantity, UnitPrice, TaxRate (same script on each)
// Reads: Quantity, UnitPrice, TaxRate. Writes: Subtotal, TaxAmount, GrandTotal.
function num(fieldName) {
var text = (panel[fieldName].RuntimeValue || "").toString().replace(/[$,\s]/g, "");
var n = parseFloat(text);
return isNaN(n) ? 0 : n;
}
var subtotal = num("Quantity") * num("UnitPrice");
var taxAmount = subtotal * num("TaxRate") / 100;
var grandTotal = subtotal + taxAmount;
// true = do not run behaviors on the calculated fields
builder.SetFieldRuntimeValue("Subtotal", subtotal.toFixed(2), true);
builder.SetFieldRuntimeValue("TaxAmount", taxAmount.toFixed(2), true);
builder.SetFieldRuntimeValue("GrandTotal", grandTotal.toFixed(2), true);
How it works¶
numreads a field as a string, removes$,,and spaces, and converts it. An empty or bad value counts as0.- The script computes every output from every input each time, so it gives the same result whichever input changed.
toFixed(2)turns each number into a string with two decimals.SetFieldRuntimeValueneeds a string.- The third argument
truestops the behaviors on the output fields from running, so no chain or loop starts.
Test it¶
- In the editor, select Test. In the preview panel, type
3inQuantityand19.99inUnitPrice.Subtotalshows59.97. - Type
10inTaxRate.TaxAmountshows6.00andGrandTotalshows65.97. - Change
Quantityto4. All three totals update.
You are done when changing any input updates all three totals, in the preview panel and in the Index app.
What can go wrong¶
Watch out
- The totals update for one field only. The script is attached to one input only. Add it to every input.
- "could not be fired" on the field. A field name in the script does not match the content type.
- A total is
0.00. A value has text the pattern does not remove, such as a currency code. Add it to thereplacepattern. - Rounding differs from the ERP.
toFixed(2)rounds each value. If the ERP rounds only the grand total, round onlygrandTotal. - Server runs recalculate. Run Indexing Behaviors and Index Your Documents write every value back, so the totals follow any input a workflow step changed. Start QC Task writes the changed totals only for documents with no invalid field.
Variations¶
Build a text field from two others. The same pattern fills Full Name from First Name and Last Name. Attach it to both name fields. It writes only when the result differs, so it does not touch a document that is already correct.
// Attach to: First Name, and the same script to Last Name
// Reads: First Name, Last Name, Full Name. Writes: Full Name.
var firstName = (panel["First Name"].RuntimeValue || "").toString().trim();
var lastName = (panel["Last Name"].RuntimeValue || "").toString().trim();
var fullName = (firstName + " " + lastName).trim();
if (fullName !== (panel["Full Name"].RuntimeValue || "")) {
builder.SetFieldRuntimeValue("Full Name", fullName, true);
}
Total without tax. Delete the TaxRate and TaxAmount lines and write subtotal to the total field.