CnFormPage
A manifest-driven runtime form. Renders a flat fields[] array plus a submit button declared in pages[].config for type: "form" pages. Closes the gap that forces every consumer's runtime-form route (public surveys, "request a quote" pages, ticket-create routes that don't need a detail-page round-trip) onto type: "custom".
Mounted automatically by CnPageRenderer when a manifest page declares type: "form". Field rendering is delegated to cnRenderFormField from @conduction/nextcloud-vue/composables so the same input set CnSettingsPage uses (boolean, number, string, password, enum, json) is available without duplication, plus a form-only file type (see "File fields" below). Submit dispatch picks one of two paths depending on which prop is set:
submitEndpoint— the page callsaxios[method](url, payload)with:paramNamesegments resolved against$route.params.submitHandler— the page resolves the name in the customComponents registry and calls the resolved value with(payload, $route, $router).
payload above is the effective payload — formData with any field currently hidden by a visibleWhen condition removed (see "Conditional fields" below).
Wraps: CnPageHeader, NcButton, NcLoadingIcon, plus the input components the field-renderer dispatches to (NcCheckboxRadioSwitch, NcTextField, NcSelect, CnJsonViewer, CnFileField, optionally NcTextArea).
Since manifest-form-logic, type: "form" pages also support multi-step wizards (config.steps[]), conditional field visibility (fields[].visibleWhen), and per-field validation rules (fields[].validation) — all three are additive: a manifest with none of them renders exactly as before.
When to use this page type
| Surface | Page type |
|---|---|
Admin / config persistence (writes to IAppConfig) | type: "settings" (CnSettingsPage) |
| End-user form, single submit, manifest-declarable fields | type: "form" (this component) |
| Form builder / authoring UI (drag-drop questions, branching logic) | type: "custom" — bespoke component |
| Detail page editing on a known register/schema | type: "detail" (CnDetailPage) |
Use type: "form" when the entire route is "render this list of fields, send the result somewhere." If the form needs sections, save/discard chrome, or per-field IAppConfig persistence, reach for type: "settings" instead.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
recoverDraft | Boolean | false | Keep what the user typed in the browser and offer it back when the form reopens (local only; nothing reaches the server). Off by default because a public form can run on a shared kiosk. A footer indicator (aria-live="polite") reads Saving, then Saved just now. The draft is cleared after a successful submit. |
draftAppId | String | '' | The app the draft belongs to; part of the draft's storage key. |
draftUserId | String | '' | Who is typing; part of the storage key so a shared browser profile never leaks a draft between users. Empty: the signed-in Nextcloud user. |
draftScope | String | 'form' | Names this form in the draft's storage key (for example the form id), so two forms never share a draft. |
fields | Array | [] | Form fields. Each MUST conform to the formField $def; optionally carries visibleWhen and validation (see below) |
steps | Array | [] | Multi-step wizard groups: { id, title, description?, fields: string[] }[]. fields[] entries are KEY REFERENCES into the fields prop. Empty (the default) renders today's single-step form unchanged — no step indicator, no Next/Back |
submitHandler | String | '' | Registered handler name resolved against the customComponents registry |
submitEndpoint | String | '' | URL the form data is dispatched to. :paramName segments resolve from $route.params |
submitMethod | String | 'POST' | HTTP method for endpoint mode. Must be `POST |
mode | String | 'public' | `edit |
submitLabel | String | 'Submit' | Submit button label (i18n key) |
smartPaste | Object | null | Fill the form from pasted text: { enabled, fields, hint?, handler }. See Paste to fill. |
successMessage | String | 'Thank you!' | Success banner copy (i18n key) |
initialValue | Object | {} | Pre-filled form state. Used by mode: "edit" |
calculate | Function | null | Host function (fieldKey, answers) => Promise<value> for fields declaring calculate.inputs. See Live values. |
unmetConditions | Array | [] | Conditions the host reports as unmet, [{ message }], shown above the submit button. |
blockSubmit | Boolean | false | Disable submit while unmetConditions is not empty; the first message is the reason. |
title | String | '' | Page title forwarded to CnPageHeader |
description | String | '' | Page description forwarded to CnPageHeader |
translate | Function | null | Optional translator applied to field labels and i18n keys |
customComponents | Object | null | Explicit registry override. Takes precedence over injected cnCustomComponents |
submitHandler and submitEndpoint are mutually exclusive at the validator level. The component itself prefers submitEndpoint when both are set so a stale manifest doesn't crash.
Manifest example — public survey (handler mode)
{
"id": "PublicSurvey",
"route": "/public/survey/:token",
"type": "form",
"title": "Survey",
"config": {
"fields": [
{ "key": "name", "label": "Your name", "type": "string", "required": true },
{ "key": "rating", "label": "Rating", "type": "number" },
{ "key": "comment", "label": "Comments", "type": "string", "widget": "textarea" }
],
"submitHandler": "submitPublicSurvey",
"mode": "public",
"successMessage": "Thanks for your feedback!"
}
}
…and in the consumer's customComponents.js:
import { generateUrl } from '@nextcloud/router'
export default {
submitPublicSurvey: async (formData, $route, $router) => {
const url = generateUrl(`/apps/pipelinq/public/survey/${$route.params.token}`)
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ answers: formData }),
})
if (!response.ok) {
throw new Error('Submit failed')
}
},
}
The handler receives $route + $router so it can read URL params and route away on success.
Manifest example — endpoint mode
{
"id": "ContactRequest",
"route": "/contact",
"type": "form",
"title": "Get in touch",
"config": {
"fields": [
{ "key": "email", "label": "Email", "type": "string" },
{ "key": "message", "label": "Your message", "type": "string", "widget": "textarea" }
],
"submitEndpoint": "/api/contact",
"submitMethod": "POST",
"successMessage": "We'll be in touch soon."
}
}
The page calls axios.post('/api/contact', formData) on submit. Use the :param substitution when the URL depends on the route — submitEndpoint: '/api/customer/:id/feedback' resolves :id from $route.params.id automatically.
Slots
| Slot | Scope | Purpose |
|---|---|---|
#header | { title, description } | Override the default CnPageHeader |
#actions | none | Right-aligned actions area (the renderer wires pages[].actionsComponent here) |
#field-<key> | { field, value, onInput, error } | Replace the default input for a specific field. error (manifest-form-logic) is the current validation failure message, or null |
#submit | { submitting, dirty, submit } | Replace the submit button entirely (only rendered on the last step of a wizard, or always in a single-step form) |
Events
| Event | Payload | When |
|---|---|---|
@input | { key, value } | A field changed |
@step | { from, to } | Wizard step navigation (Next/Back) — manifest-form-logic |
@submit | the effective payload | Submit succeeded. Hidden-by-condition field keys are removed (see "Conditional fields") |
@error | error | Submit failed (the component already displays the error message in the form's error block) |
Multi-step wizards
config.steps[] groups the flat fields[] array into ordered wizard steps. Steps hold ordered key references, not field objects — config.fields[] stays the single source of truth:
{
"id": "IntakeWizard",
"route": "/public/intake/:token",
"type": "form",
"config": {
"fields": [
{ "key": "kind", "label": "Kind", "type": "enum", "enum": ["person", "company"] },
{ "key": "name", "label": "Name", "type": "string", "validation": { "required": true } },
{ "key": "kvk", "label": "KvK", "type": "string",
"visibleWhen": { "field": "kind", "op": "eq", "value": "company" },
"validation": { "required": true, "pattern": "^[0-9]{8}$" } }
],
"steps": [
{ "id": "who", "title": "Who are you?", "fields": ["kind", "name"] },
{ "id": "kvk", "title": "Company details", "fields": ["kvk"] }
],
"submitEndpoint": "/api/intake/:token"
}
}
Rules (enforced by validateManifestV2() post-schema, since JSON Schema can't express them):
steps[].idmust be unique within the page.- Every
steps[].fields[]entry must reference a declaredfields[].key. - When
stepsis present, every declared field key must appear in exactly one step — a field in zero steps would silently never render; a field in two steps would double-render.
Rendering: an accessible step indicator (<nav aria-label="Form steps"> wrapping an <ol>, the current step's <li> carrying aria-current="step"), only the current step's fields, and a Back / Next / Submit footer. Back never validates; Next validates the current step's visible fields and blocks on failure; Submit (last step) validates every visible field across every step and, on failure, jumps to the earliest invalid step. A step whose fields are all hidden by visibleWhen conditions is skipped by Next/Back in both directions.
Absent steps, CnFormPage renders exactly as it did before this capability existed — one field column, one submit button.
Conditional fields
fields[].visibleWhen reuses the library's shared visibleWhen predicate ({ endpoint? | source? | field, op?, value }, op one of eq | neq | gt | gte | lt | lte, default eq) — the same shape manifest actions, the banner widget, and rowClassRules already use. No new grammar.
- LOCAL mode (neither
endpointnorsourceset) —fielddot-paths into the live form data, so a condition can reference another field's current value ({ "field": "kind", "op": "eq", "value": "company" }). Evaluated synchronously on every keystroke, in field declaration order: a field hidden by its own condition reads asundefinedfor every LATER field's condition, so hiding one field can cascade and hide another. Author fields in the order they're referenced. endpoint/sourcemodes keep their existing async, fail-safe semantics (GETa JSON endpoint, or query an OpenRegister{ register, schema, filter? }source) — resolved once at mount and cached; they do not re-evaluate on keystrokes. Any fetch error hides the field (fail-safe), matching the banner widget's documented behaviour. On a public-mode page these fetch with the requester's (anonymous) auth, so prefer LOCAL conditions on public forms unless the endpoint is meant to be publicly readable.
The first dot-segment of a LOCAL field must match a declared field key — a typo ("filed"/wrong key) fails at validateManifestV2() time rather than silently evaluating undefined forever.
Hidden fields are excluded from validation and from the dispatched payload (their draft value is retained in component state, so toggling the condition back restores what the user typed). This is deliberate: a required rule on an invisible field can never soft-lock the form, and the backend never receives a stale, retracted answer.
Validation
fields[].validation is a closed shape: { required?, min?, max?, pattern?, message? } (additionalProperties: false — a typo'd rule key fails validation instead of being silently ignored).
field.type | required passes when | min / max bound | pattern |
|---|---|---|---|
string, password | non-empty after trim | string length | tested against the value |
number | value is a finite number | numeric value | not applicable |
boolean | value is true (consent checkboxes) | not applicable | not applicable |
enum | a value is selected | not applicable | not applicable |
json | value is non-null | not applicable | not applicable |
file | a file is present | not applicable | not applicable |
message (i18n-able, resolved through the same translate prop as field.label) replaces the built-in default message for whichever rule fails. Built-in defaults are English msgids translated via t('nextcloud-vue', …).
Cross-shape rules the JSON Schema can't express are checked post-schema by validateManifestV2(): min <= max when both are set, pattern must compile, and type-inapplicable rules are errors (pattern only on string/password; min/max only on string/password/number).
Errors render through the pure validateFieldValue(field, value, translate) helper (src/utils/formValidation.js) on Next / Submit; editing a field clears its error immediately. For NcTextField/NcTextArea-family widgets the error surfaces via the native error + helperText props; for widgets without native error support (boolean, enum, json, file, the native-<textarea> fallback, and #field-<key> slot overrides) CnFormPage renders an adjacent role="alert" element wired to the input via aria-describedby.
A caveat: a validation.pattern beginning with a literal @ (e.g. "@[a-z]+") trips the manifest's sentinel-token guard, which walks every string leaf under pages[].config. Regex authors anchor with ^ anyway ("^@[a-z]+$" starts with ^, not @), so this is theoretical in practice.
Field types
The renderer delegates to cnRenderFormField from @conduction/nextcloud-vue/composables. Supported field.type values:
field.type | Widget | Notes |
|---|---|---|
boolean | NcCheckboxRadioSwitch | |
number | NcTextField (type=number) | Empty string → null; otherwise coerced to Number |
string | NcTextField | Default. Add widget: "textarea" to render a multi-line input |
password | NcTextField (type=password) | |
enum | NcSelect | Options from field.enum (preferred) or field.options |
json | CnJsonViewer | Read-only display in this revision |
file | CnFileField | The value is the picked file as a data: URL. Form pages only. See "File fields" |
Unknown field.type values fall back to NcTextField and emit a one-shot console.warn so the manifest typo surfaces during development.
File fields
A file field lets the person filling in the form attach one file.
{ "key": "report", "label": "Advice report", "type": "file", "accept": ".pdf,.docx", "maxSize": 10485760 }
The field reads the file in the browser and holds its content as a data: URL. That string travels in the payload like any other value. Nothing is uploaded when the file is picked, so a cancelled form writes nothing.
The field never holds a path or a URL. It cannot choose where the file ends up: the receiver of the payload does. Point submitEndpoint at an OpenRegister object whose schema has a property of type: "file", and OpenRegister stores the content in that object's own folder, under a name it generates itself. It checks the property's allowed types and size limit first, and refuses executable content. A submitHandler receives the same data: URL and decides for itself.
acceptnarrows the picker, in HTMLacceptsyntax:.pdf,application/pdf,image/*. The field checks it again after the pick, because the picker's filter can be switched off.maxSizeis the largest file the field reads, in bytes. It defaults to 1 MB, the library's cap for a file carried inline. Raise it when the form expects scanned documents.- Both checks help the person filling in the form. The server still decides what it accepts.
- A value that is not a
data:URL, such as a file the object already holds inmode: "edit", shows by its title and is sent back untouched until the user replaces or removes it. Remove file sets the value tonull.
type: "file" is rejected on type: "settings" pages: those save to app config, which has no place for file content.
Live values
A form can fill in what it can work out. All of it is additive: a field without these keys behaves as before.
assign. A field lists { when, value } rules. When an answer a rule reads changes, the first rule whose when holds (the same local condition visibleWhen takes) sets the field. value is a literal, @answer.<field> (another answer) or a sentinel token. Once the person edits the field by hand its rules stop until the form is reset (a new initialValue). A rule never reads its own output, so it cannot loop. The field says "Filled in from Country" so a screen reader learns why it changed.
{ "key": "currency", "label": "Currency", "type": "string",
"assign": [
{ "when": { "field": "country", "op": "eq", "value": "NL" }, "value": "EUR" },
{ "when": { "field": "country", "op": "eq", "value": "US" }, "value": "USD" }
] }
Token defaults. default accepts @me, @me.displayName, @me.email, @today, @now and @object.<field> (from initialValue), resolved once when the form opens. The e-mail comes from the user's profile and arrives a moment after open. A value in initialValue always wins, so an edit form never overwrites stored data.
{ "key": "email", "label": "E-mail", "type": "string", "default": "@me.email" }
calculate. A field with calculate.inputs is the host's to compute. When one of those answers changes, CnFormPage calls the calculate prop after 400 ms of quiet and writes the result into the field, which renders read-only. A rejection keeps the last value and shows "Could not calculate". The library has no formula language: what calculate does (for buildiq, its rule engine in preview mode) belongs to the host.
{ "key": "fee", "label": "Fee", "type": "string", "calculate": { "inputs": ["size", "type"] } }
Unmet conditions. unmetConditions lists what the host says is not yet satisfied, above the submit button. With blockSubmit, submit is disabled while the list is not empty and its title is the first message. The host decides what is unmet; the page only shows it.
Paste to fill
A signed-in user can fill a form from pasted text, for example an email signature. The maker declares it in the page config:
"smartPaste": { "enabled": true, "fields": ["naam", "adres", "telefoon"], "hint": "Paste the customer's email.", "handler": "fillCustomer" }
handler names an entry in the customComponents registry: a function (text, fields) => Promise<{ values }>, or { fill, available } where available() resolves true when the service can be used. fields holds the allowed fields only, each as { key, label, type, options } (options lists an enum's allowed values). No value already in the form is ever passed, and the form does not store the pasted text. The library calls no model; whatever the handler calls is governed where it lives.
The "Paste to fill" button shows only when enabled is true, mode is not public, the handler resolves and available() (when given) resolves true; a missing, throwing or unavailable handler hides it and warns once. In the dialog the user pastes the text and clicks Fill. Returned values land only in allowed, visible fields that are empty (or in all allowed visible fields when the user ticks "Replace what I typed"), and only when the value fits the field's type (string, number, boolean, enum; other types are never filled) and passes the field's validation. A skipped proposal is counted in the notice ("3 fields filled, 1 skipped"). Each filled field carries a "Suggested" tag with an Accept button; editing the field, Accept or Accept all clears it. Nothing is submitted automatically. The validator rejects an undeclared field key, enabled without a handler, and enabled on a public form.
Board look
With the board look the page draws the board field anatomy and, on a failed submit or Next, an error summary at the top: a heading ("There are 2 errors"), one sentence and a link per error that moves focus to its control. The summary takes focus. Without the board look the page keeps its single error line.
| Prop | Default | What it does |
|---|---|---|
optionalLabel | optional | The word in "(optional)". Required fields carry no mark. |
optionalNoticeLabel | A field without (optional) must be filled in. | Shown once above the first field of a mode: "public" form that has a required field. |
showOptionalNotice | true | Set false to hide the sentence. |
cancelRoute | empty | Where the footer's Cancel goes. A cancel listener also shows Cancel. |
A form with steps draws the board stepper, and the form sits in a white card (1px border, radius 12, padding 24) that ends in a hairline footer: Cancel or Previous on the left, Next (with a chevron) or the submit button on the right.
Field sizes are tokens: --cn-field-label-size (14px), --cn-field-height (40px), --cn-field-text-size (15px), --cn-field-hint-size (13px) and --cn-field-error-border (2px). Portaliq's citizen theme sets the larger values (17px text, 48px inputs, 19px labels, 3px error borders).
Why type: "form" is its own page type
The settings page (type: "settings") is admin-facing config persistence — it assumes IAppConfig is the destination and groups fields into sections. Forms have a different audience (end users), a different destination (consumer-defined endpoint or handler), and a flat shape (no sections). Sharing the field renderer keeps the duplication low without wedging end-user form rendering into a settings-shaped component.
For form-builder authoring UIs (drag-drop question ordering, per-field validation panels, branching logic) keep using type: "custom" — the manifest's declarative shape doesn't fit a builder UI.