Field metadata — every option explained
Configure field types and properties — text, numbers, dates, relationships, files, and more
A Field defines an individual property within an Object. ObjectStack provides a comprehensive set of field types covering text, numbers, dates, selections, relationships, files, calculations, and specialized types like vectors and QR codes.
Basic Usage
Fields are defined inside an Object's fields map using Field.* factory methods:
import { ObjectSchema, Field } from '@objectstack/spec/data';
export const Contact = ObjectSchema.create({
name: 'contact',
sharingModel: 'private',
label: 'Contact',
fields: {
first_name: Field.text({ label: 'First Name', required: true }),
last_name: Field.text({ label: 'Last Name', required: true }),
email: Field.email({ label: 'Email', unique: 'organization' }),
phone: Field.phone({ label: 'Phone' }),
birth_date: Field.date({ label: 'Date of Birth' }),
is_active: Field.boolean({ label: 'Active', defaultValue: true }),
account: Field.lookup('account', { label: 'Account', required: true }),
},
});Field Types
Text Types
| Type | Factory | Description |
|---|---|---|
text | Field.text() | Single-line text |
textarea | Field.textarea() | Multi-line text |
email | Field.email() | Email address with validation |
url | Field.url() | URL with validation |
phone | Field.phone() | Phone number |
password | Field.password() | Masked password input |
markdown | Field.markdown() | Markdown editor |
html | Field.html() | HTML content |
richtext | Field.richtext() | Rich text (WYSIWYG) editor |
name: Field.text({ label: 'Name', required: true, maxLength: 255 }),
bio: Field.textarea({ label: 'Bio', maxLength: 5000 }),
website: Field.url({ label: 'Website' }),
notes: Field.markdown({ label: 'Notes' }),Number Types
| Type | Factory | Description |
|---|---|---|
number | Field.number() | Integer or decimal |
currency | Field.currency() | Monetary value with currency support |
percent | Field.percent() | Percentage value |
quantity: Field.number({ label: 'Quantity', min: 0, max: 10000, step: 1 }),
price: Field.currency({ label: 'Price', min: 0 }),
// percent stores a fraction: 0.15 = 15% (the UI renders it as a percentage)
discount: Field.percent({ label: 'Discount', scale: 2, min: 0, max: 1 }),Currency Configuration:
price: Field.currency({
label: 'Price',
currencyConfig: {
currencyMode: 'fixed', // 'fixed' pins the column to defaultCurrency;
// 'dynamic' (default) shows the tenant default;
// 'record' reads each record's own code
defaultCurrency: 'USD', // the column's currency under 'fixed'
},
}),
// Each invoice in its own currency: the code lives in a sibling text field
currency_code: Field.text({ label: 'Currency', valueDomain: 'iso_4217_currency' }),
amount: Field.currency({
label: 'Amount',
currencyConfig: { currencyMode: 'record', currencyField: 'currency_code' },
}),The stored value is a bare number in every mode — never { value, currency }.
Under dynamic (the default) the amount displays in the tenant's
localization.currency setting and defaultCurrency is not the displayed
currency; fixed pins the column to defaultCurrency; record takes each
record's ISO 4217 code from the field currencyField names, a text field
declaring valueDomain: 'iso_4217_currency' (currency_code is a convention,
not a required name). A record-mode amount refuses a write with a blank code and
an aggregate that does not group by the code: see
Currency fields.
Date & Time Types
| Type | Factory | Description |
|---|---|---|
date | Field.date() | Date only |
datetime | Field.datetime() | Date and time |
time | — | Time only |
start_date: Field.date({ label: 'Start Date', required: true }),
created_at: Field.datetime({ label: 'Created At', readonly: true }),Deadlines: dueLike and settledWhen
A date is a deadline only when its field says so. dueLike: true on a
date or datetime field declares one: once the date has passed, a renderer
may show it as overdue, with relative wording ("Overdue 3d") and an overdue
colour. Without the key the field is not a deadline, and nothing is inferred
from its name — a due_date that is not declared is just a date.
A deadline usually stops mattering when the record is finished, and only the
object knows what finished means. settledWhen says it: a CEL predicate over
the record, in the same family as visibleWhen, and while it is TRUE no
overdue wording or colour applies to that record.
import { P } from '@objectstack/spec';
import { Field } from '@objectstack/spec/data';
due_date: Field.date({
label: 'Due Date',
dueLike: true,
settledWhen: P`record.status == 'done'`,
}),Both keys are judged when the metadata is authored, not when a view renders it:
- Either key on any other field type is refused, and so is
settledWhenwithoutdueLike: true— a settle condition on a date that is no deadline would change nothing. settledWhenis checked exactly likevisibleWhen: it must parse, read fields asrecord.<field>, name fields the object declares, and read no root butrecord(plusprevious, andparenton a master-detail line item).objectstack validate,objectstack buildand saving the object all refuse anything else, naming the field.
Both are display semantics: nothing on the write path reads them, and a past deadline never blocks a save.
Boolean Type
is_active: Field.boolean({ label: 'Active', defaultValue: true }),Selection Types
| Type | Factory | Description |
|---|---|---|
select | Field.select() | Single or multi-select dropdown |
radio | — | Radio button group |
checkboxes | — | Checkbox group |
// Single select
status: Field.select({
label: 'Status',
options: [
{ label: 'New', value: 'new', color: '#999', default: true },
{ label: 'Active', value: 'active', color: '#0A0' },
{ label: 'Closed', value: 'closed', color: '#A00' },
],
}),
// Multi-select
skills: Field.select({
label: 'Skills',
multiple: true,
options: [
{ label: 'JavaScript', value: 'js' },
{ label: 'Python', value: 'python' },
{ label: 'Go', value: 'go' },
],
}),Options must use { label, value } objects. Values are stored in the database and must be lowercase.
Relationship Types
| Type | Factory | Description |
|---|---|---|
lookup | Field.lookup() | Many-to-one reference |
master_detail | Field.masterDetail() | Parent-child with cascade delete |
// Simple lookup
account: Field.lookup('account', {
label: 'Account',
required: true,
}),
// Filtered lookup — structured filters, cascading from another field
primary_contact: Field.lookup('contact', {
label: 'Primary Contact',
dependsOn: ['account'],
lookupFilters: [
{ field: 'is_active', operator: 'eq', value: true },
],
}),
// Filtered by the record being edited: books valid on the quote's date, or with no start date
price_book: Field.lookup('price_book', {
label: 'Price Book',
lookupFilters: [
{ field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' }, orEmpty: true },
],
}),
// A pick fills sibling fields: the picked product's list_price lands in unit_price
product: Field.lookup('product', {
label: 'Product',
required: true,
lookupAutofill: [{ target: 'unit_price', source: 'list_price' }],
}),
// Master-detail (cascade delete)
project: Field.masterDetail('project', {
label: 'Project',
required: true,
}),
// Inline line items on the parent form (the parent names the child in a
// field group: fieldGroups: [{ key: 'lines', relatedList: 'order_line' }])
order: Field.masterDetail('order', {
label: 'Order',
required: true,
inlineEdit: 'grid',
inlineTitle: 'Lines',
inlineAmountField: 'line_total',
}),| Property | Type | Description |
|---|---|---|
reference (1st arg) | string | Target object name |
lookupFilters | { field, operator, value, orEmpty? }[] | Base filters restricting which records are selectable (structured, picker-honored). value is a literal or a { $record } reference — see below |
dependsOn | (string | { field, param? })[] | Sibling fields that scope the candidates by equality; the picker is gated until they are set |
deleteBehavior | enum | 'set_null', 'cascade', 'restrict' |
inlineEdit | 'grid' | 'form' | Form factor of the child rows on the parent create/edit form: 'grid' or 'form'; left out, it is picked from the child's shape (a boolean is refused at parse). The form inlines the child only where a field group of the parent names it (fieldGroups[].relatedList); inlineEdit alone inlines nothing |
inlineColumns | array | Optional explicit columns for the inline grid |
inlineAmountField | string | Optional numeric child field for the inline running total |
lookupAutofill | { target, source, overwrite? }[] | Fields of this object a pick fills from the picked record (single-value lookup / master_detail only) — see below |
Lookup filters that read the record being edited
A lookupFilters value can be { $record: 'field' }, or one lookup hop away,
{ $record: 'lookup_field.field' }: a value of the record being edited, which the picker
of a record form sends in place of the reference.
- The reference is the whole
valueand pairs only witheq,ne,gt,lt,gteorlte. Outside a record form (inline edit, an action's parameter dialog, a bulk action) the entry is left out. - An empty value drops the entry: while the referenced value is empty or cannot be read, the other entries alone filter.
orEmpty: truealso matches a candidate whose column is null; it pairs with the same six operators.- Not
dependsOn. The picker re-queries when a referenced field changes. Listing that field independsOnas well would add an equality filter on it to the candidate query.
Details and a fuller example: Filtered Lookups.
Lookup-pick autofill: lookupAutofill
A single-value lookup / master_detail can declare lookupAutofill: [{ target, source, overwrite? }]. When a user picks a record in that field, each pair copies
the picked record's source field (a field of the reference object) into this
object's target field — in the record form, and in a line-item grid column over
the field. The example above fills a quote line's unit_price from the picked
product's list_price.
targetis a field of this object that an author writes: not the lookup itself, notreadonly, and not computed (formula,summary,autonumber, or a stored field with anexpression). Each target is named once per field. The object's parse refuses anything else.sourceis a field the referenced object declares and the record carries (notinternal), and its value must be one the target can hold: the same type and multiplicity (a list only into a list), a string-valued field into a text target,numberandcurrencyinto each other, a relationship only into a relationship over the same object.os validate/os buildjudge the source against the referenced object.- Overwrite rule. By default a pick never replaces a value somebody wrote: the
target is filled only while it is empty or still holds the value an earlier pick
filled in. A pair with
overwrite: truereplaces the target on every pick. - Currency rule. An amount of money (a
currencyfield, or aformulareturningcurrency) is copied only into a target in the same currency: both in the home currency, or both naming the same code (afixedcode, or the code the record or itsmaster_detailparent holds). Otherwise the target is left as it is and the form says why, naming both currencies and the picked amount so the price can be entered by hand. Nothing is converted. Anumbercarries no currency and copies as before. The grid's same-named copy follows the same rule. - Client-side only. The fill edits the form, and the filled value is saved as an ordinary write. Nothing on the write path reads the key: an import or an API write that sets the lookup fills nothing.
- In a line-item grid, the column key
autofillstill governs only the grid's same-named copy; a declared pair applies under its own overwrite rule and takes its target out of that copy. A master-detail collection whoserelationshipFieldis set and whose every column carries itstypeloads no child fields, so it sees no pairs and keeps only the same-named copy.
The key's full contract is in the Field reference.
Referential integrity
reference is enforced on write. A create or update that sets a
lookup / master_detail to an id with no matching row in the target object is
rejected with 400 VALIDATION_FAILED and a fields[] entry whose code is
reference_not_found (see the error catalog). A
write that is not a system write may name, in a lookup, master_detail or
user field, only a record its caller can read: one the caller cannot read is
rejected the same way, before the record's validation rules run. The
same check runs on bulk updates. An update judges only the references it adds: a
value the row already stores, carried back unchanged, is not judged again, so a
deleted user's id left in a user field does not block later edits of the record.
That comparison reads only stored values the caller may read: in a column the
caller may edit but not read, every value is judged as new.
Clearing a relationship is not a dangling reference: null, "" and [] all mean
"no link". Which of them deleteBehavior: 'set_null' writes when the referenced
record goes away depends on the field: a single-value lookup is set to null, while
a multiple: true lookup keeps its other members and loses only the deleted one —
and on an optional field a set emptied that way is stored as null, the same as one
never set (the multiple doc block in packages/spec/src/data/field.zod.ts, rendered
in the Field reference).
deleteBehavior governs what happens to this record when the referenced
record is deleted; the integrity check above governs what may be written
here in the first place. They are two halves of the same relationship contract.
A user field takes part only when it declares a deleteBehavior. Declared, it
works as it does on a lookup when the user is deleted: cascade deletes the
records holding that user, set_null clears the field (a multiple: true field
loses only that member), and restrict refuses the user delete with
409 DELETE_RESTRICTED; a set_null on a required user field refuses it too. A
user field that declares none keeps the deleted user's id, as it always has.
File & Media Types
| Type | Factory | Description |
|---|---|---|
image | Field.image() | Image file upload |
file | Field.file() | Generic file upload |
avatar | Field.avatar() | User avatar/profile image |
video | — | Video file |
audio | — | Audio file |
photo: Field.image({ label: 'Photo' }),
resume: Field.file({ label: 'Resume' }),
profile_image: Field.avatar({ label: 'Profile Image' }),Calculation Types
| Type | Factory | Description |
|---|---|---|
formula | Field.formula() | Calculated from other fields |
summary | Field.summary() | Roll-up from child records |
autonumber | Field.autonumber() | Sequential auto-generated number |
// Formula
total: Field.formula({
label: 'Total',
expression: 'record.quantity * record.price * (1 - record.discount / 100)',
}),
// Summary (roll-up)
total_amount: Field.summary({
label: 'Total Amount',
summaryOperations: {
object: 'order_item',
field: 'amount',
function: 'sum',
relationshipField: 'order',
},
}),
// AutoNumber
case_number: Field.autonumber({
label: 'Case Number',
autonumberFormat: 'CASE-{0000}',
}),Summary fields are server-owned. The engine recomputes them when child records
are inserted, updated, or deleted. relationshipField is optional when the child
has only one lookup/master_detail field pointing back to the parent; set it
when multiple relationships target the same parent object.
A summary field is read-only on create and on update whether or not it declares
readonly: true. A value that a POST, an import (any writeMode), an MCP
create or update (over HTTP or stdio), a PATCH or a bulk update sends for it
is dropped, the rest of the write is stored, and the response's droppedFields
names the field with reason readonly. Two more doors end in the same create
and drop the value the same way: the overrides of a clone, whose answer names
the field in droppedFields as a create's does, and a public form submission,
which is anonymous and answers with the created record's id alone, so the
person who submitted it is not shown the drop. A record created with its value
dropped starts as if no value had been sent: 0
for count and sum, empty for min, max and avg, and the next child write
replaces it with the computed value. Under strictReadonlyWrites the whole write
is refused. Seed data never stores a summary value, and that includes the seed
data a package install loads, since it goes through the same seed loader: a value a
seed record supplies for a summary field is not written, on create or on
update, and the rest of the record is. The summary is computed from the seeded
child records, so a parent seeded with a total and no children shows the
empty-set value (0 for count and sum, empty for min, max and avg),
and re-seeding a parent leaves its computed value in place. The load logs one
warning per dataset that names the object, the fields and how many values it
did not write. One degraded path does not go through the seed loader: when the
runtime has no metadata service, or the seed loader throws, it falls back to a
basic insert of the seed records, and that fallback still stores a supplied
summary value. To show a total, seed the child records it sums. Server code that runs with isSystem: true can still write the column,
as it can any read-only column: a historical import (treatAsHistorical: true,
which only the system principal may send) keeps a pre-computed total, on create
and on update. Undoing an ordinary
import restores the rows through an ordinary update, so a summary value that an
import committed before this rule overwrote is not put back by the undo; it stays
until the next child write recomputes it.
Because the roll-up is engine-derived state rather than a user write, the
recompute runs under a system context: a user who may create a child does not
also need edit access on the parent, and the aggregate is computed over the
whole child collection rather than the writer's visible subset. The permission
decision that governs the write is the one on the child. The parent's own
row is unaffected — a user still needs edit access to change any other field on
it — and the summary column stays subject to the parent's field-level security
on read.
So a permission set that cannot read the aggregated child field, a child field
the roll-up's filter tests, or the child object (whether through its object
grant, its field entries or a requiredPermissions capability it does not hold),
or that reads only some child rows, still reads the roll-up; os lint,
os validate and os build tell you about each such set
(the security-rollup-source-unreadable warning, and the security-rollup-source-row-scoped
note — see the one gate, four doors).
If the value should not be visible, set readable: false on the summary field in
that set: it hides the field from every holder of the set, and another set they
hold with no entry for the field does not restore it, so declare readable: true
on the field in the sets whose holders should keep it.
If the set is meant to read the total without its children (an account total
shown to staff who may not see invoice rows), acknowledge that on the same entry
with the reason, and the warning for that set and column becomes a note quoting
it, so os lint --strict passes:
fields: {
'crm_account.invoiced_amount': {
readable: true,
rollupSourceUnreadableReason: 'Service staff read account totals but not invoice rows',
},
},Only these authoring checks read the key. The entry that carries it is still an
ordinary field permission, though, and votes readable: true: on a set that had
no entry for the summary, adding one restores the column for holders whose other
sets mask it. Every other set and column is still reported, and a blank reason,
or one beside readable: false, is refused.
A child validation rule can read a parent summary one hop through its
reference, for example "each supplier has at most one primary contact" as a
count summary filtered on { is_primary: true } plus the child rule
record.is_primary == true && record.supplier.primary_contact_count > 0.
A bulk create equals one-by-one creates (批量等于逐条): inside one bulk
insert (an import batch, createManyData, insertManyData) each row's rules
read the summary as it stands after the earlier rows of the same batch that the
rules admitted, accumulated in memory, so two primary contacts in one import
create one row and refuse the other with the rule's error. A row the rules
refuse is not counted. A detail object's requiredWhen that reads the summary
on parent (the master-detail header, for example
requiredWhen: 'parent.line_count >= 2') reads it the same way, so the third
of three bare lines in one batch is refused as the third single insert is.
A rule that reads a formula or a stored computed field of the parent calculated
from the summary (record.budget.remaining, parent.headroom < 50) reads it
calculated over the summary as the earlier rows moved it, so a row is refused,
or admitted, as the same row inserted on its own after them would be.
This holds for count, and for sum, min and max
over number values. An avg summary, a sum/min/max meeting a value that
is not a number, and a summary whose filter reads through another reference,
as a dotted path or in the nested form { account: { status: 'x' } }, keep
reading the stored value, as they did before; a field calculated from one of
them and from a summary that moves reads the first as stored. A preview of the
batch (validate in insert mode) judges each row the same way, except that a
column of the master-detail header the caller is not served reads as empty at
every row.
An import's dry run previews its create rows in the batches the import
writes them in (200 rows each) and refuses the rows the import refuses, with
the same message. It writes nothing, so a row in a later batch reads the
summary as stored before the import: two such rows that fall in different
batches of a dry run both preview valid, while the import refuses the second.
A bulk update equals one-by-one updates (批量等于逐条): a bulk update
(updateManyData, the update operation of batchData, a grid bulk edit)
recomputes the parents' summaries once, when the batch ends, unless a rule
reads one of the summaries that child object rolls up: a validation rule of any
object reading it one hop through a reference, a detail object's
requiredWhen / readonlyWhen reading it on parent, or a rule of the parent
object itself reading its own summary (a cap such as record.line_count <= 5,
or a declared bound such as min / max / precision / unique on the
summary, a declared unique index naming it, or any stored computed field of the
parent calculated from it, whose value the recompute's write judges whatever it
declares). A rule that reads a
formula or a stored computed field calculated from the summary reads the
summary too, and so does a rule on a summary that a chain of summaries rolls
the first one up into. A stored computed field of any object that reads the
summary one hop (record.invoice.line_count) counts as well, since it stores
what it reads at its own write. Then every roll-up of that child object
recomputes after each row, so each row's rules, and the parent's own rules
judging each recompute, read it as one-by-one updates would, for every summary
function, avg included. A parent. predicate that reads a field that is not a
summary, and is not calculated from one, does not count.
A predicate update equals one-by-one updates too: an update that selects
its rows by a filter (update(object, patch, { where, multi: true }), a flow
update_record step with multi: true) judges every matched row before its
one write. A validation rule reading a parent summary one hop through a
reference, a detail object's requiredWhen reading it on parent, and a rule
reading a formula or stored computed field of the parent calculated from it,
read it as the matched rows judged before leave it, for every summary function,
avg included, and a row that moves to another parent leaves the old one and
joins the new one. If any row is refused, none is written. Four cases keep
reading the stored value for every parent the update reads that summary for,
as a by-id update reads it: a summary the patch cannot move (it writes neither
the reference to the parent, nor the summed field, nor a field the summary's
filter reads, as a key or as a { $field } comparand), a
summary whose filter reads through another reference, as a dotted path or in
the nested form { account: { status: 'x' } } (or one the in-memory filter
cannot evaluate), a summary meeting a value that is not a number, and a min / max
when one parent holds more than 5,000 matched rows. A rule of the parent
itself judges the summary once, after the write.
Hooks and flow steps read the value from before the batch: inside one bulk
create or bulk update, a hook or flow step that reads a parent's summary reads
it as stored before the batch, on create and update alike.
Concurrent writes are not guaranteed (并发不保证): two writes in flight at
the same time each read the summary they started from, so a guard like the one
above can still admit one row from each.
Specialized Types
| Type | Factory | Description |
|---|---|---|
address | Field.address() | Structured address (street, city, state, country) |
location | Field.location() | Geographic coordinates (lat/lng) |
color | Field.color() | Color picker (hex/rgb/hsl) |
rating | Field.rating() | Star rating (1-5) |
slider | Field.slider() | Range slider |
signature | Field.signature() | Digital signature capture |
qrcode | Field.qrcode() | QR/barcode generator |
code | Field.code() | Code editor with syntax highlighting |
json | Field.json() | JSON data |
vector | Field.vector() | AI embedding vectors |
tags | — | Tag list |
progress | — | Progress bar |
office: Field.address({ label: 'Office Address' }),
coordinates: Field.location({ label: 'Location' }),
brand_color: Field.color({ label: 'Color' }),
satisfaction: Field.rating(5, { label: 'Rating' }),
approval_signature: Field.signature({ label: 'Signature' }),
embedding: Field.vector(1536, { label: 'Embedding' }),Common Properties
These properties are available on all field types:
Constraints
| Property | Type | Default | Description |
|---|---|---|---|
required | boolean | false | Field must have a value |
unique | boolean | false | Values must be unique across records |
defaultValue | any | — | Default value for new records |
maxLength | number | — | Maximum character length |
minLength | number | — | Minimum character length |
valueDomain | 'iana_time_zone' | 'iso_4217_currency' | 'iso_3166_alpha2' | — | Standard the written value must be a member of (text only): an IANA time zone, an ISO 4217 currency code or an ISO 3166-1 alpha-2 country code. The same closed vocabulary a settings specifier's valueDomain uses; membership, not a pattern, is what a write is judged against |
min | number | — | Minimum numeric value |
max | number | — | Maximum numeric value |
Display
| Property | Type | Default | Description |
|---|---|---|---|
label | string | — | Human-readable display name |
description | string | — | Developer documentation |
inlineHelpText | string | — | Help text shown in UI |
hidden | boolean | false | Hide from default views |
readonly | boolean | false | Prevent editing — hidden from create/edit forms AND server-enforced on both write paths: a non-system write to the field is silently dropped on UPDATE and, since the maintainer ruling of 2026-09-03, on INSERT — both in the engine, so a direct engine.insert caller (a flow's create_record, a hook body's ctx.api) is covered exactly like the data API's REST/MCP/import faces. A stripped field still falls back to its defaultValue; seeding a readonly column at create requires a system context (import/migration/programmatic seed). Platform (sys_/managedBy) objects are governed by their own write policy instead — the resolved-affordance write guard keyed off the object's lifecycle bucket (ADR-0103), not this field-level flag. |
sortable | boolean | true | Allow sorting by this field |
group | string | — | Group name for organizing in forms (e.g. 'billing') |
Search & Index
| Property | Type | Default | Description |
|---|---|---|---|
searchable | boolean | false | Search this field when the object declares no searchableFields — any type but secret / password / vector; a declared searchableFields is the whole set |
externalId | boolean | false | Not read: nothing matches on it. A seed dataset names its match field in its own externalId, an import in its mapping's upsertKey |
Database indexes are declared at the object level in the object's indexes[] array — there is no per-field index flag. See Indexing.
Package upgrades
| Property | Type | Default | Description |
|---|---|---|---|
renamedFrom | string[] | — | Earlier keys of this field (snake_case), e.g. renamedFrom: ['company'] on a field now keyed account_name: on a package upgrade from a version that has the old key and not this one, the platform carries the old column's data to this field instead of adding an empty column. Each entry once; never the field's own key, a key another field of the object still declares, or an old key another field also claims — each refused at parse. Read only at package upgrade: the schema sync renames the old column to this field, values and all, or refuses by name before any change (both columns present, two old columns, a platform column, a destructive type change). Keep an entry while any installed version may still carry the old key: an upgrade from such a version carries the column only while the entry is declared |
Security
| Property | Type | Default | Description |
|---|---|---|---|
requiredPermissions | string[] | — | Capabilities required to read/edit this field — masked on read, denied on write unless the caller holds all of them (ADR-0066 D3) |
trackHistory | boolean | — | Opt a media or JSON field into old → new values on the record activity timeline; other fields show them already, and false does not hide them |
fieldHistory | boolean | — | This field's old → new values on the record activity timeline: absent shows them, false turns them off |
For values that must be encrypted at rest (API keys, tokens, DB passwords), use the
secret field type — see the Field Type Gallery.
Conditional Logic
| Property | Type | Description |
|---|---|---|
visibleWhen | string | Expression | CEL predicate; field is shown only when TRUE |
readonlyWhen | string | Expression | CEL predicate; field is read-only when TRUE |
requiredWhen | string | Expression | CEL predicate; field is required when TRUE |
settledWhen | string | Expression | CEL predicate on a dueLike date; the deadline is settled when TRUE — see Deadlines |
conditionalFormatting | { condition, style }[] | Cell formatting rules; the first rule whose CEL condition is TRUE styles this field's cell — see Cell formatting |
multiple | boolean | Allow multiple values (for select, lookup, file) |
import { P } from '@objectstack/spec';
import { Field } from '@objectstack/spec/data';
close_reason: Field.select({
label: 'Close Reason',
visibleWhen: P`record.status == 'closed'`,
requiredWhen: P`record.status == 'closed'`,
options: [
{ label: 'Won', value: 'won' },
{ label: 'Lost', value: 'lost' },
{ label: 'Cancelled', value: 'cancelled' },
],
}),
invoice_total: Field.currency({
label: 'Invoice Total',
readonlyWhen: P`record.status == 'paid'`,
}),Conditional field rules are evaluated in both tiers. ObjectUI forms update
visibility, read-only state, and required markers live as the draft record
changes, including row-scoped rules inside inline master-detail grids. The
server enforces requiredWhen on submit and ignores writes to fields whose
readonlyWhen predicate is TRUE, so client-side affordances are not the
only guard. Use requiredWhen. The deprecated conditionalRequired alias was removed in
protocol 17 (#3855): authoring it is rejected with an error naming the
replacement, not silently stripped, and os migrate meta --from 16 lists the
mechanical edits for existing sources.
Who the lock applies to — and the derived-field write path
A TRUE readonlyWhen predicate locks the field for every API-boundary
caller. Unlike static readonly, passing { context: { isSystem: true } }
does not exempt it: a state lock any system-context write could bypass would
not be a state lock, and the frozen-paid-invoice case depends on it.
What the lock does not cover is the server's own trusted code. A value a
beforeUpdate hook derives — or writes over a key the caller also sent — is a
server value, not a caller write, and is never stripped. That is what makes
"visible on the form but locked, and recomputed by a hook" a spelling the
platform supports on one field:
// The field renders locked, and only the hook may move it.
next_maintenance_date: Field.date({
label: 'Next Maintenance',
readonlyWhen: P`true`,
}),// The hook is the write path.
beforeUpdate: (ctx) => {
if ('period_days' in ctx.input.data) {
ctx.input.data.next_maintenance_date = addDays(today, ctx.input.data.period_days);
}
},A client cannot use this to launder a write. The engine snapshots the caller's payload at entry, before any middleware or hook runs, and judges a key only while it still holds that value — so echoing the locked key back never exempts it, and if a hook overwrites it, the value that persists is the hook's. Either way the caller's value does not land.
Locking a detail from its master: parent
On a detail object — one that declares a master_detail relationship — a
readonlyWhen predicate may read the header record as parent. The canonical
case is "once the invoice is Paid, its lines are frozen":
quantity: Field.number({
label: 'Qty',
required: true,
// `parent` = the record on the other end of this object's master_detail field.
readonlyWhen: P`parent.status == 'paid'`,
}),The server binds parent on the update path by reading the master the row
points at (a repointing write is judged against the master it lands on), so the
lock holds against a direct API call, not only in the grid.
Two rules make this predictable:
- Exactly one master.
parentresolves only when the object declares exactly onemaster_detailrelationship. With none — or with two, where the metadata does not say which one is "the parent" —objectstack compilerejects the predicate with an error naming the object. - An unresolvable
parentmeans locked, not open. If the header cannot be read at write time, the field is treated as read-only rather than written. A lock the platform could not evaluate is never waived: that is what makes the declaration a guarantee instead of a hint.
Cell formatting: conditionalFormatting
conditionalFormatting styles a field's cell by a rule: an ordered list of
{ condition, style }, the same rule a list view's conditionalFormatting
declares for its rows. The first rule whose CEL condition is TRUE applies
its CSS style map to this field's cell wherever the field renders — a grid, a
kanban card, the record page, a related list or a report cell. A list view's
row rules style the row, and both may apply to one record.
The condition reads two roots: value, this field's value on the record, and
record, the row.
import { P } from '@objectstack/spec';
import { Field } from '@objectstack/spec/data';
amount: Field.currency({
label: 'Amount',
conditionalFormatting: [
{ condition: P`value < 0`, style: { color: '#b91c1c' } },
],
}),The rules are checked when the metadata is authored, like visibleWhen:
- A rule is exactly
{ condition, style }, the condition is not blank, andstylemaps CSS property names to string values. Anything else is refused at parse. - The condition must parse, read other fields as
record.<field>, name fields the object declares, and read no root butvalueandrecord.objectstack validate,objectstack buildand saving the object all refuse anything else, naming the field and the rule.
The rules are for presentation: an amount below zero in red, stock under its
safety level in amber, a priority cell coloured by its value. A state with a
meaning of its own belongs in a declaration instead — a deadline's overdue
state is dueLike with settledWhen,
from which the wording and the colour both follow. Nothing on the write path
reads the rules.
The console's cell renderers read these rules in a later ObjectUI release. Until then a rule is validated when it is authored and styles no cell.
Naming Conventions
- Field names use
snake_case:first_name,annual_revenue,is_active - Boolean fields use
is_orhas_prefix:is_active,has_children - Lookup fields use the object name directly:
account(notaccount_id) - Configuration keys use
camelCase:maxLength,defaultValue
Related
- Object Metadata — Define business entities
- Validation Metadata — Field-level and cross-field validation rules
- View Metadata — Control how fields are displayed in views