Live Calculated Fields
Compute a form field's value live in the browser as other fields change, from a simple product to a sum over a nested child table.
set_formular()
->set_formular($targetField, $expression, $event = null, $watchFields = null) is a live, client-side computed field: whenever $event fires on any of $watchFields's own controls in the open form, $expression is evaluated and written into $targetField. Any bare field name in $expression (e.g. quantity) is automatically substituted with that field's current value - no manual parsing needed.
$xcrud->set_formular('total', 'quantity*price');
| Parameter | Type | Default | Description |
|---|---|---|---|
$targetField | string | - | The field the computed value is written into; must be a whitelisted, editable field |
$expression | string | - | A JS expression; bare field names are substituted with their current value |
$event | ?string | null | DOM event that triggers recompute; null defaults to 'input' (recomputes on every keystroke) |
$watchFields | ?string | null | Comma-separated fields to watch; null auto-detects every field $expression itself references |
$expression is trusted, developer-authored JavaScript - it is never influenced by request/user data, so it's sent to the client unsigned and run directly, not through a sandboxed evaluator.
Explicit event and watch list
Omit $event/$watchFields for the common case above. Spell them out when the fields to watch aren't simply "every field the expression mentions," or to opt into a less chatty recompute (e.g. only on blur):
$xcrud->set_formular(
'email',
'"{firstName}".toLowerCase() + ".{lastName}@myoffice.com".toLowerCase();',
'onmouseout',
'firstName'
);
Writing a computed value into a target field only works for controls with a single plain value (text/textarea/number/date/datetime/time/password/year/price/a single select) - boolean/radio/switch/checkboxes/multiselect/relation/upload fields aren't supported as a formula target.
Aggregating a nested table
A formula can also aggregate a direct nested_table() child's own field, referenced as childTableName.fieldName using sum()/avg()/count()/min()/max() syntax:
$xcrud->set_formular('totalAmount', 'sum(orderdetails.priceEach)');
This recomputes totalAmount live whenever the "orderdetails" nested tab's row data changes (initial load, or after adding/editing/deleting a line item), for as long as the parent's edit form stays open. It only updates the open form's own target control - it does not itself save the parent row. Only one level deep is supported, and count() ignores fieldName (still required for a consistent childTable.field shape) - it always counts rows. See Nested Tables Overview for setting up the child table itself.