Calculated fields
A field whose value is computed rather than read from the row. There is no
separate type and no registry — it is an ordinary PivotField carrying five
extra members, pushed into the same fields array as everything else.
The compiler is free; the designer modal is Enterprise. If you are defining fields in code, everything on this page works in the Community package.
Row-level or summary-level — decide first
This is the one decision that matters, and getting it wrong gives you a column of plausible-looking wrong numbers.
| Row-level | Summary-level | |
|---|---|---|
| Member | calculateExpression | calculateSummaryExpression |
| Runs | once per row, during encoding | once per cell, after aggregation |
| Sees | the row object | the other data fields' aggregated values |
| Then | is aggregated like any measure | overwrites the cell outright |
Needs summaryType | yes | no |
A ratio or a percentage must be summary-level. A row-level margin computes
per-row percentages and then adds them together, because the engine's default
summaryType is sum. EMEA's 60% and APAC's 37.5% become 97.5%.
In code
import { compileSafeFormula } from '@kanunilabs/pivotgrid-core';
import type { PivotField } from '@kanunilabs/pivotgrid-react';
const revenue: PivotField<Sale> = {
id: 'revenue', dataField: 'revenue', caption: 'Revenue',
dataType: 'number', area: 'data', areaIndex: 0, summaryType: 'sum',
};
// Row-level: a plain function, aggregated afterwards like any measure.
const profit: PivotField<Sale> = {
id: 'profit', caption: 'Profit', dataType: 'number',
area: 'data', areaIndex: 1,
summaryType: 'sum', // state it — the default is 'sum' either way
isCalculated: true,
calculateExpression: (row) => row.revenue - row.cost,
format: { style: 'currency', currency: 'USD' },
};
// Summary-level: the correct shape for a ratio.
const MARGIN = '([Revenue] - [Cost]) / [Revenue] * 100';
const fieldMap = new Map([['Revenue', 'revenue'], ['Cost', 'cost']]);
const margin: PivotField<Sale> = {
id: 'margin', caption: 'Margin %', dataType: 'number',
area: 'data', areaIndex: 2,
isCalculated: true,
formulaType: 'summary',
formulaString: MARGIN,
calculateSummaryExpression: compileSafeFormula(MARGIN, fieldMap)!,
format: { style: 'decimal', maximumFractionDigits: 2 },
};
The parts need not be columns. A summary formula reads only data fields,
so [Revenue] and [Cost] must be in the data area — but mark them
helper: true and they are computed for the formula and drawn nowhere: no
column, no data-area chip, no field-chooser entry, nothing in an export.
getCell and getEngineResult hold only the shown fields.
{ id: 'cost', dataField: 'cost', caption: 'Cost', dataType: 'number',
area: 'data', summaryType: 'sum', helper: true }
Give every field an id equal to its dataField. Row formulas bind on
dataField || id, summary formulas bind on id. Keeping them identical means
one fieldMap serves both, and moving a formula between the two levels stops
being a rewrite.
formulaString and formulaType are what gets recompiled on reload — a bare
calculateExpression function does not survive a page refresh. Supply both if
the field should persist.
One field, two roles
A price is a good row or filter field ("only lines priced 2.50"), but in the
Values area its plain sum means nothing: you want the weighted average,
Σ amount / Σ qty. Give the field both a dataField and a
calculateSummaryExpression, and it is one entry in the field list that
switches role with its area:
- In the filter, row or column area it works on the raw
dataFieldvalues: its members, the header filter list (blanks included), sorting and grouping are those ofprice. - In the Values area every cell, subtotal and grand total is the formula.
So are everything that reads the cells: the selection statistics, display
modes, top N, sorting by summary,
getSummaryTable, the charts and the Excel pivot export. The drill-down andgetRecordsForCellsstill give the source rows.
const fields: PivotField<Line>[] = [
{ id: 'price', dataField: 'price', caption: 'Price', dataType: 'number',
area: 'data', summaryType: 'sum',
calculateSummaryExpression: (v) => v.amount / v.qty },
// The parts: computed for the formula, drawn nowhere.
{ id: 'amount', dataField: 'amount', caption: 'Amount', dataType: 'number',
area: 'data', summaryType: 'sum', helper: true },
{ id: 'qty', dataField: 'qty', caption: 'Qty', dataType: 'number',
area: 'data', summaryType: 'sum', helper: true },
];
When the raw value is itself a row calculation (a day count from two
dates, a price after tax), the field has no dataField: give it
isCalculated: true with the row-level calculateExpression and the
calculateSummaryExpression. Its members, header filter (a row the
calculation leaves empty is a "(Blank)" member) and sorting are the row
calculation's values; in Values it shows the formula. A weighted day count:
{ id: 'days', caption: 'Days', dataType: 'number', area: 'filter', summaryType: 'sum',
isCalculated: true, formulaType: 'row',
calculateExpression: (row) => (row.shipped ? daysBetween(row.ordered, row.shipped) : null),
calculateSummaryExpression: (v) => v.daysQty / v.qty },
// daysQty: a row-level helper, days × qty (0 where there is no date).
{ id: 'daysQty', caption: 'Days × qty', dataType: 'number', area: 'data', summaryType: 'sum',
helper: true, isCalculated: true, formulaType: 'row',
calculateExpression: (row) => (row.shipped ? daysBetween(row.ordered, row.shipped) * row.qty : 0) },
Dragging the field, the menu's "Move to", allowedAreas, setFields and the
saved state (getPersistedState / applyPersistedState) keep both roles:
nothing about the field changes when it moves, only the area. With a
dataField, leave out isCalculated: it is not needed, and it shows the
field with the calculated-field icon. A calculated field whose formulas are
functions (either shape) is the app's: the field chooser and the field menu
offer no "Edit calculation" and no delete for it, because the designer can
only read back a formula text (formulaString). Because the formula is a
function, it comes from your field definition, not from the saved state.
Replacing a formula with setFields recomputes at once; removing it turns the
field back into a plain measure (its summaryType over the raw values).
A function formula is recognised by its source text, so building the same
fields again on every render does not recompute. Two functions with the same
source that read different outside values count as the same formula: put the
value in the formula text, or give the field a different id.
In the row or column area the header shows the raw member as it is ("2.5"),
while the header filter list writes it with the field's format ("2,50 ₺").
To show the formatted text in the header too, and group by it, set
groupByFormat: true:
{ id: 'price', dataField: 'price', caption: 'Price', dataType: 'number',
format: { minimumFractionDigits: 2, maximumFractionDigits: 2, suffix: ' ₺' },
groupByFormat: true, calculateSummaryExpression: (v) => v.amount / v.qty }
// Rows: "2,50 ₺", "4,00 ₺"
With a serverSource, the request lists the field under rows, columns
or filters with its dataField like any other field; under values it is
sent with its dataField and summaryType too, and the browser replaces the
server's number with the formula over the helpers' totals. A server only has
to return the helpers.
The formula language
The whole grammar:
numbers 1 2.5 100
field refs [Revenue] — by CAPTION, in square brackets
operators + - * / %
grouping ( )
That is all of it. There are no functions — no SUM, IF, ABS, ROUND,
MIN, MAX — no comparisons, no ternaries, no strings, no dates, and no way
to reference another cell. It is a hand-written recursive-descent parser
compiled to a closure tree, so nothing goes near eval or new Function.
Validate before you commit a formula:
import { testSafeFormula } from '@kanunilabs/pivotgrid-core';
try {
testSafeFormula(input, fieldMap); // throws with a message
} catch (err) {
setError((err as Error).message);
}
Dividing by zero gives a blank cell, not 0. A summary formula or function
that has no number — a division by zero, null, NaN, ±Infinity, a throw —
leaves the cell empty on screen, in the footer's selection totals and in every
export, and sorts as the smallest value. A row-level formula still reads a
division by zero as 0, so the measure it feeds keeps adding up.
compileSafeFormula returns null instead of throwing — use it when you have
already validated, and testSafeFormula when a human is typing.
The designer modal (Enterprise)
Passing renderCalculatedFieldModal is what makes the footer's calculator
button appear. EnterprisePivotGrid does this for you.
import { EnterprisePivotGrid } from '@kanunilabs/pivotgrid-react-enterprise';
<EnterprisePivotGrid
licenseKey={key}
data={data}
initialFields={fields}
onFieldsChange={(next) => {
// The only signal that a user added, edited or deleted a calculated field.
persist(next.filter((f) => f.isCalculated));
}}
/>
onSave hands you a finished PivotField with isCalculated, formulaString
and the compiled function already in the right slot.
What this does not do
- A saved report destroys every calculated field. Reports are persisted by
JSON.stringify, which drops the compiled functions, and loading one never recompiles fromformulaString. The column comes back as zeros, with no error. And it is not opt-in: a default report is loaded after the state store has correctly rehydrated, so a user who set one loses their calculated fields on every page load. PersistformulaString+formulaTypeyourself fromonFieldsChangeif these must outlive the browser. - Formulas bind by CAPTION. Renaming a field silently invalidates every formula that references it, and the field settings dialog lets a user rename anything with no cross-check.
- A typo reports the wrong error. An unknown caption comes back as "Formula contains unsafe characters", not "unknown field".
- Everything non-numeric becomes zero. Every field read is
Number(x) || 0, sonull, missing and text all collapse to0rather than to a blank cell. Division and modulo by zero also yield0. - The modal never sets
summaryType. A ratio created through the designer is therefore summed. Create ratios in code, or edit the field afterwards. - A summary expression cannot read another summary expression. The context is a snapshot taken before any expression writes to it.
- Row-level expressions run on the main thread. They are evaluated during column encoding, before the data is handed to the worker — functions cannot be serialised across that boundary. A heavy row expression is felt directly.
- Only data-area fields are visible to a summary expression. Row and column fields are not in the context.
- Top N's "Others" row cannot run a formula named by a plugin id. A
calculateSummaryExpressiongiven as a string (a registered'summary'plugin) leaves that one row blank and reports it; pass the function itself if you use "Others".
Without a licence key the modal still works, watermarked.