Form Calculated Totals Developer Guide - edmozley/freeitsm GitHub Wiki
Calculated totals, option values and bundles - Developer Guide
GH #160 Part D, built 23 Nov 2026 for 5.10.0. The design: Financial approvals, section 7. For people building forms: Forms -> Calculated totals and the in-app help topic Calculated totals and prices (forms/help/totals.php).
A catalogue item in FreeITSM is a form, so an order takes one of three shapes:
- the form is the item;
- the form offers a few items;
- the form is a basket.
A fourth shape is the bundle: a whole workplace set, where each item is also in the catalogue on its own.
All four are one new question type, calculated, whose answer the server works out from the other answers. It needs no new table and no new column. The total is an ordinary stored answer, so the CSV, the PDF, approval-step conditions and {{submission.fields.Order total}} all read it with no extra code.
1. 📁 The files involved
| File | What it does |
|---|---|
includes/form_calculated.php |
New. FormCalc: option values, checking a total's settings, remapping its question pointers, working the total out, bundle prices, annotate() for the fillers, text() for reading |
includes/services/forms.php |
'calculated' in FIELD_TYPES; never required; validateFieldConfig() calls cleanOptionValues() / cleanConfig(); syncFields() and createVersion() remap the lines; submitForm() throws away a posted total and works it out |
assets/js/form-logic.js |
'calculated' in TYPES; optionValues(), calcTotal(), calcText(), calcShown(), calcBox(), renderCalcs(); canReference() refuses a total as a condition trigger |
forms/fill.php, self-service/catalogue.php |
Draw the read-only box, and refresh every total on each visibility pass |
forms/edit/index.php |
The Add menu, the line editor, the Value box beside each option, the preview |
api/forms/get_form.php, api/self-service/get_catalogue_form.php |
FormCalc::annotate() adds each bundle item's current price (calc_prices) |
assets/js/form-pdf.js, forms/submissions.php |
Show the total as money; the CSV keeps the plain number |
includes/catalogue_approvals.php, includes/services/task_forms.php |
The approval card, the ticket body and task evidence read it as money |
self-service/includes/footer.php, forms/fill.php, forms/submissions.php, forms/collection.php |
Load Money::scriptTag() + money.js (the design's "money on the portal" trap) |
tests/form-calculated.php |
22 checks |
2. 🗄️ Where it is stored - form_fields.config
A choice question (dropdown or choose-one) holds its option values in its config:
{"option_values": {"Standard": "900", "Pro": "1500"}}
They are keyed by the option's text, because that is what an answer stores and what a condition compares. The builder moves a value when its option is renamed (updateOption()), as it already did for an option marked as an exception. cleanOptionValues() drops values on options that no longer exist and refuses a negative.
A Calculated question holds its lines:
{"calc_lines": [
{"kind": "fixed", "amount": "120", "times": 812},
{"kind": "option", "field": 810, "times": 811},
{"kind": "grid", "field": 813, "value_col": 2, "qty_col": 3},
{"kind": "item", "form_id": 398, "qty": "2", "times": 737}],
"calc_currency": "EUR",
"calc_hide": true}
field and times point at other questions on the form, by id. A question that is new in the same save is sent as "idx:N", the scheme conditions already use. It is resolved in syncFields() pass 2, and remapped through the same $idMap in createVersion():
if ($hasCalc) $config = FormCalc::remapRefs($config, fn($ref) => $idMap[(int)$ref] ?? (int)$ref);
form_id on an item line names a catalogue item. At work-out time FormCalc::leafOf() follows that item to its newest version, so a bundle names an item once and keeps following it as it is edited.
3. ⚙️ Working it out - FormCalc::compute()
submitForm() does three things:
- Throws away anything posted for a calculated question, before visibility is worked out.
- Skips it in the required and format checks.
- After those checks, and before the approval gate, works each visible total out from
$normalised, which by then holds only the answers to questions that were asked:
foreach ($fields as $cField) {
if (($cField['field_type'] ?? '') !== 'calculated' || empty($visible[(int)$cField['id']])) continue;
$cTotal = FormCalc::compute($conn, $cField, $fieldsById, $normalised);
if ($cTotal !== null) $normalised[(int)$cField['id']] = $cTotal;
}
Because it runs before catalogueStepsPlan(), an approval step's Only when Order total is more than 5000 compares the real total.
The rules:
| Case | Result |
|---|---|
| A question hidden by a condition | Adds nothing (it is not in $normalised) |
| A blank quantity, or an option with no value | Adds nothing |
| A table row with no quantity | Adds nothing |
| A table cell that is not a number | Blank total (null, nothing stored) |
| A bundle item with no price, or in another currency | Blank total. Never converted, never guessed |
A blank total makes a threshold step run (catalogueStepApplies() treats an unreadable number as "applies"), which is the safe direction.
Exact amounts. Each amount is turned into minor units (pence, cents) from its decimal text (minor()), multiplied, rounded per line, and added as integers. The result is written to the currency's own decimal places with a ., for example "3000.00" or "1500" in JPY. Money::format() shows it in each reader's own format.
4. 🖥️ The live total
form-logic.js calcTotal() is a courtesy copy of compute(), with the same rules, so the person sees the total change as they answer. Each filler draws FormLogic.calcBox(f), an <output data-calc-id>. It is never a data-field-id, so no filler ever collects or sends it. Each visibility pass calls:
FormLogic.renderCalcs(document, fields, values, vis);
Bundle prices come from the server with the form (calc_prices, added by FormCalc::annotate()), so the browser never needs the catalogue.
A total with Show the total to the person filling in the form unticked (calc_hide) still has a hidden wrapper, so FormRender is not told the surface cannot draw it. It is still worked out and kept.
5. ⚠️ Traps
| Trap | Rule |
|---|---|
| Trusting the browser's total | Never. submitForm() unsets it before anything else reads the answers |
| Field ids change per version | A total's lines are remapped wherever conditions are: syncFields() (idx:N) and createVersion() ($idMap). A third copy path must do the same |
| Option values keyed by text | Rename-follow lives in the builder (updateOption()); the server drops values on options that no longer exist |
| A total as a condition trigger | Not allowed: ANSWERABLE_TYPES leaves it out on the server, canReference() in the builder. It changes as the person types, and the server decides visibility before it works totals out |
| Five type lists | 'calculated' is in the service, form-logic.js and the builder's known. The AI generator does not offer it (a total needs other questions wired up), so tests/forms-lookup/run.php reports it missing there, beside grid and image, which it already reported |
| Float money | Never add floats of amounts: minor() works from the text |
| Money on the portal | money.js is now loaded by the portal footer whenever a page loads form-logic.js |
6. ✅ How it was verified
tests/form-calculated.php (22 checks) covers:
- option values saved, pruned and refused when negative;
idx:Nstored as ids, a wrong-type pointer refused, and a total with no lines refused;- option × quantity, plus a fixed amount × a shown quantity, and a hidden question adding nothing;
- a total reading back as money;
- a basket table, and a table line refused without a number column;
- a bundle at the items' own prices, following an item's new version and price, with an earlier request keeping its frozen total;
- no price, and another currency, each giving a blank total;
- a new version remapping its lines and keeping option values;
- a 3,001 total skipping a "more than 5000" step and a 6,002 total running it.
The other form and approval tests still pass:
| Test | Checks |
|---|---|
| layout | 43 |
| drafts | 21 |
| audiences | 15 |
| grid export | 12 |
| webhook | 9 |
| lookups | 4 suites |
| task forms | 99 |
| task embed | 9 |
| ticket forms | 30 |
| card | 71 |
| C1 steps | 37 |
| C2 people | 41 |
| group approvals | 38 |
| answer edits | 26 |
forms-logic/run.php |
85 |
Driven on a test install:
- the portal showed €6,000.00 for Pro × 4 and submitted it, and the request stored 6000.00 and ran the board step;
- a bundle showed €3,520.00 for two desks;
- the analyst filler showed €2,700.00;
- the staff inbox and the submissions list showed money;
- in the builder, a form saved unchanged, and a new quantity question plus a new total in one save stored the right id.
See also
- Financial approvals - design - section 7, and the worked example in section 8
- Approval steps and chains - Developer Guide - Only when on a total
- Form sections and conditional logic - Developer Guide - the id /
idx:Nscheme this reuses