Collect records with forms

A form view asks for some of a table's fields and adds a record when it is sent. Use it for records other people start: a bug report, an expense, a job application. This page builds a hiring tracker's application flow. Candidates apply through a form, the record lands in the Candidates table, and recruiters move it across a Kanban by stage.

Open the live example: Hiring tracker (Base)

In the demo, pick the "Apply" view, fill in the form and press Submit, then switch to "Hiring pipeline": the new candidate is a card in Applied.

SvGrid Base is part of the Suite edition of @svgrid/enterprise. Without a key it runs with a watermark.

1. Declare the Candidates table

Keep the fields in one module. The base imports them, and so do the public page and the server you build later on this page, so all three agree on field ids and types.

// src/lib/hiring.ts
import type { BaseTable } from '@svgrid/enterprise/base'

export const STAGES = [
  { value: 'Applied', color: '#94a3b8' },
  { value: 'Phone screen', color: '#18bfff' },
  { value: 'Onsite', color: '#2d7ff9' },
  { value: 'Offer', color: '#fcb400' },
  { value: 'Hired', color: '#20c933' },
  { value: 'Rejected', color: '#f82b60' },
]
export const SOURCES = [{ value: 'Careers page' }, { value: 'Referral' }, { value: 'Job board' }]

export const candidateColumns: BaseTable['columns'] = [
  { field: 'name', header: 'Candidate', fieldType: 'text' },
  { field: 'email', header: 'Email', fieldType: 'email' },
  { field: 'phone', header: 'Phone', fieldType: 'phone', description: 'With the country code.' },
  { field: 'role', header: 'Role', fieldType: 'link', fieldProps: { table: 'roles', multiple: false, inverse: 'candidates' } },
  {
    field: 'resume', header: 'Resume', fieldType: 'attachment',
    fieldProps: { accept: '.pdf,.doc,.docx', maxFiles: 1, maxSize: 10 * 1024 * 1024 },
    description: 'One PDF or Word file, up to 10 MB.',
  },
  { field: 'portfolio', header: 'Portfolio', fieldType: 'url', description: 'A site, a repository or a design portfolio.' },
  { field: 'years', header: 'Years of experience', fieldType: 'number', fieldProps: { format: 'integer', allowNegative: false } },
  { field: 'start', header: 'Earliest start', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },
  { field: 'notes', header: 'Notes', fieldType: 'longText' },
  // The team's fields. The form leaves them out.
  { field: 'stage', header: 'Stage', fieldType: 'singleSelect', fieldProps: { options: STAGES, default: 'Applied' } },
  { field: 'source', header: 'Source', fieldType: 'singleSelect', fieldProps: { options: SOURCES } },
  { field: 'recruiter', header: 'Recruiter', fieldType: 'user' },
  { field: 'applied', header: 'Applied', fieldType: 'createdTime' },
]

export const roleColumns: BaseTable['columns'] = [
  { field: 'name', header: 'Role', fieldType: 'text' },
  { field: 'candidates', header: 'Candidates', fieldType: 'link', fieldProps: { table: 'candidates', multiple: true, inverse: 'role' } },
]

/** What a candidate fills in, in order. */
export const APPLY_FIELDS: string[] = ['name', 'email', 'phone', 'role', 'resume', 'portfolio', 'years', 'start', 'notes']

The form labels each field with the column's header, the type's icon in front of it. A column's description is the help text: the form shows it in small grey type under the field, and the grid shows it on the info mark in the header.

2. Add the form view

A form is a view, next to the pipeline and the grid:

<script lang="ts">
  import { SvBase, enableBase, setFieldUsers, type BaseTable } from '@svgrid/enterprise/base'
  import { APPLY_FIELDS, candidateColumns, roleColumns } from '$lib/hiring'

  enableBase()
  setFieldUsers([{ id: 'u1', name: 'Ana Ruiz' }, { id: 'u2', name: 'Ben Okafor' }])

  let { candidates, roles }: { candidates: Record<string, unknown>[]; roles: Record<string, unknown>[] } = $props()

  let tables = $state.raw<BaseTable[]>([
    {
      id: 'candidates',
      name: 'Candidates',
      primaryField: 'name',
      data: candidates,
      columns: candidateColumns,
      views: [
        { id: 'pipeline', name: 'Pipeline', type: 'kanban', stackBy: 'stage' },
        { id: 'all', name: 'All candidates', type: 'grid', color: { mode: 'field', field: 'stage' } },
        {
          id: 'apply',
          name: 'Apply',
          type: 'form',
          formFields: APPLY_FIELDS,
          formTitle: 'Join the team',
          formDescription: 'Tell us about yourself. We reply to every application within a week.',
          formRequired: ['name', 'email', 'role', 'resume'],
          formSubmitLabel: 'Send application',
        },
      ],
    },
    { id: 'roles', name: 'Roles', primaryField: 'name', data: roles, columns: roleColumns },
  ])
</script>

<SvBase bind:tables editable expandRows containerHeight={640} onTablesChange={(t) => console.log('save', t)} />

Pick "Apply" in the view menu. The grid stays mounted underneath and the form covers it: a card with "Join the team" as the heading, the description under it, and one box per field. A click on a box opens the editor the cell uses: the select panel for a select, the record picker for Role, the date picker for Earliest start, the attachment dialog for Resume, the number box for Years of experience. Tab and Shift+Tab move to the next or previous field from inside an editor.

The demo's Apply form view: Candidate filled in as Ana Ruiz, Email as ana@ with a red border and

Whoever may change views can do all of this without code: "Customize form" in the view bar opens a dialog with the title, the line under it, the button's text and every field a person can fill in, each with a switch to ask for it, arrows to move it and a box to require it. Each change shows in the form behind the dialog and is kept in the view as formTitle, formDescription, formSubmitLabel, formFields and formRequired.

For a form view, the view bar keeps the view menu, "Customize form" and, when the base runs automations, the Automations button. Hide fields, Filter, Sort, the record count and search are gone.

Without formFields, the form asks for every field a person can fill in: the primary field first, then the rest in the grid's column order, hidden columns included. Computed types (formula, lookup, rollup, count, autonumber, created and modified time and by, button), columns with editable: false and columns with a fieldFn are always left out, even when formFields names them. Without formTitle, the heading is the view's name.

3. See what a sent form adds

What happens when a form is sent: the fields start with the defaults and each value goes through valueParser; Submit checks required fields, the email, URL and phone formats and the column's validate; the record gets its defaults and an id and is appended to the grid, then onRowAdd runs; onSubmit settles into Thank you or the error, and in a base it runs the

A form with nothing in any field does not send: it says "Fill in at least one field before you send this." and adds no record. A field filled by a default or a link counts.

Press Submit and the form runs its checks first (What the form checks). When they pass, it builds the record the way the row adder builds a new row, from three layers, each winning over the one before:

  1. Each field's own new-row value: a fieldProps.default, today for a date with defaultToday, the next autonumber, the created time, the current user for created by.
  2. The grid's rowAdder.defaults(). In a base, set it in the table's props.
  3. What the form's fields show.

Inside <SvBase tables> every new record also gets an id, even in a table whose props set rowAdder: false.

The first two layers also fill the form when it opens: a field the form asks for starts with the value the new record would get, and the person can change it. A field the form does not ask for still gets its value, so a candidate who never sees Stage lands in Applied because of default: 'Applied'.

The record is appended to the grid, then the grid's onRowAdd fires with it, and with tables the base hands the whole list to onTablesChange:

<SvBase bind:tables editable onRowAdd={(e: { row: Record<string, unknown> }) => console.log('new candidate', e.row)} />

The form then shows "Thank you" and "The record was added." with a "Submit another" button, which starts a new record with the defaults again. A form view starts a new record each time it opens, so switching to another view drops what was typed.

A sent record holds values in the shapes the cells use:

Field type Value
text, longText, email, url, phone A string, as typed
richText An HTML string, sanitized (null when the editor was left empty)
number A number, as typed (an integer field: a whole number). Past 15 significant digits, text holding every digit
date without time '2026-11-02'
singleSelect The option's value
link An array of record ids, also with multiple: false: ['r2']
attachment An array of attachments
user The person's id

Each value goes through the same coercion and column valueParser as a cell edit, so a custom field type parses the same in a form. A field left blank is not in the record. A field that showed a default and was cleared is sent empty ('', null or [], as its editor leaves it): the person removed the default, so it does not come back.

4. Put the form on a public page

Candidates should not open your base. Give them a page that draws only the form and posts what they send to your server, while the team keeps working in the base.

SvBaseForm is the form the view draws, as a component. It reads its fields from a grid through that grid's api, so the page mounts a grid with the Candidates columns and no rows, out of sight:

<!-- src/routes/apply/+page.svelte -->
<script lang="ts">
  import { SvGrid } from '@svgrid/grid'
  import { SvBaseForm, enableBase, registerLinkedTable } from '@svgrid/enterprise/base'
  import { APPLY_FIELDS, candidateColumns } from '$lib/hiring'

  enableBase()

  let { data }: { data: { roles: Array<{ id: string; name: string }> } } = $props()

  // The record picker for Role lists the open roles, and only those. In an
  // effect: it runs in the browser only (the list is page-wide, so a server
  // render must not set it for every visitor), and it unregisters on leave.
  $effect(() => registerLinkedTable({ id: 'roles', name: 'Roles', primaryField: 'name', rows: () => data.roles }))

  // Raw: the form finds the grid by the api object itself.
  let api = $state.raw<any>(null)

  // The form waits on the Promise: thanks when it resolves, the message when it rejects.
  async function send(row: Record<string, unknown>) {
    const res = await fetch('/apply', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(row),
    })
    if (!res.ok) throw new Error('Your application did not reach us. Press Send application again.')
  }
</script>

<div class="store" aria-hidden="true">
  <SvGrid data={[]} columns={candidateColumns} onApiReady={(a) => (api = a)} />
</div>

{#if api}
  <SvBaseForm
    {api}
    fields={APPLY_FIELDS}
    required={['name', 'email', 'role', 'resume']}
    title="Apply to Acme"
    description="Tell us about yourself. We reply to every application within a week."
    submitLabel="Send application"
    onSubmit={send}
  />
{/if}

<style>
  .store { position: absolute; width: 1px; height: 1px; overflow: hidden; visibility: hidden; }
</style>
// src/routes/apply/+page.server.ts
declare const db: { openRoles: () => Promise<Array<{ id: string; name: string }>> }

export async function load() {
  return { roles: await db.openRoles() }
}

A required field shows a red asterisk after its label. Press "Send application" with Email empty and its box turns red, with "Email is required" under it; nothing is sent. Type ana@ and the line reads "Not a valid email address". The message goes away as soon as the field gets a new value.

send returns a Promise, so the form waits for the server, with the button disabled. When the Promise resolves, the form shows "Thank you". When it rejects, the form takes the row back out of the hidden grid, keeps every field as it was, and shows the error's message above the button; pressing the button again sends the same record. An error with no message shows "The record could not be sent. Try again." An onSubmit that returns nothing shows "Thank you" at once.

The form draws with the --sg-* tokens (--sg-bg, --sg-fg, --sg-border, --sg-muted, --sg-accent, --sg-accent-fg, --sg-danger, --sg-font), so the page's theme styles it.

5. Prefill hidden values from the URL

A job post links to /apply?role=r2&source=Referral. The candidate should not pick the role again, and should never see Source. Read both in load, check them, and hand them to the hidden grid as its rowAdder.defaults: the form starts every record from them, and what is typed wins over them. This load replaces the one in step 4:

// src/routes/apply/+page.server.ts
import { SOURCES } from '$lib/hiring'

declare const db: { openRoles: () => Promise<Array<{ id: string; name: string }>> }

export async function load({ url }: { url: URL }) {
  const roles = await db.openRoles()
  const role = roles.find((r) => r.id === url.searchParams.get('role'))?.id ?? null
  const asked = url.searchParams.get('source')
  const source = SOURCES.some((s) => s.value === asked) ? asked : 'Careers page'
  return { roles, role, source }
}

In the page, leave the role out of the fields when the link named one, and give the hidden grid the defaults. Source is not among the fields, so it stays hidden and still lands in the record. The rest of the page is as in step 4:

<script lang="ts">
  import { APPLY_FIELDS } from '$lib/hiring'
  // ...the other imports, registerLinkedTable, api and send from step 4

  let { data }: { data: { roles: Array<{ id: string; name: string }>; role: string | null; source: string } } = $props()

  const fields = $derived(data.role ? APPLY_FIELDS.filter((f) => f !== 'role') : APPLY_FIELDS)
  const rowAdder = $derived({
    defaults: () => ({ source: data.source, ...(data.role ? { role: [data.role] } : {}) }),
  })
</script>

<div class="store" aria-hidden="true">
  <SvGrid data={[]} columns={candidateColumns} {rowAdder} onApiReady={(a) => (api = a)} />
</div>

{#if api}
  <SvBaseForm {api} {fields} required={['name', 'email', 'resume']} submitLabel="Send application" onSubmit={send} />
{/if}

A link value is an array of ids, so the default is [data.role]. Drop 'role' from required too: a required id that is not among the fields is ignored, but leaving it there reads as if the role were still asked for.

6. Upload the resume

With no uploader, a file added in the form stays in the browser as a blob: URL, and the server receives a link it cannot open. Set an uploader on the public page:

import { setAttachmentUploader } from '@svgrid/enterprise/base'

setAttachmentUploader(async (file, { signal, onProgress }) => {
  const res = await fetch(`/apply/upload?name=${encodeURIComponent(file.name)}`, {
    method: 'PUT',
    body: file,
    signal,
    headers: { 'content-type': file.type || 'application/octet-stream' },
  })
  if (!res.ok) throw new Error(res.status === 413 ? 'Larger than 10 MB' : `Upload failed (${res.status})`)
  onProgress(1)
  const { url } = (await res.json()) as { url: string }
  return { id: url, url, name: file.name, type: file.type, size: file.size }
})
// src/routes/apply/upload/+server.ts
import { error, json } from '@sveltejs/kit'

// Returns the stored file's URL, under https://files.example.com/resumes/.
declare const storage: { put: (key: string, body: ArrayBuffer, type: string) => Promise<string> }

const TYPES = new Set([
  'application/pdf',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
])

export async function PUT({ request, url }: { request: Request; url: URL }) {
  const type = request.headers.get('content-type') ?? ''
  if (!TYPES.has(type)) error(415, 'Send a PDF or a Word file')
  const body = await request.arrayBuffer()
  if (body.byteLength > 10 * 1024 * 1024) error(413, 'Larger than 10 MB')
  const name = (url.searchParams.get('name') ?? 'resume').replace(/[^\w.-]+/g, '_').slice(0, 100)
  return json({ url: await storage.put(`resumes/${crypto.randomUUID()}-${name}`, body, type) })
}

Click the Resume box ("Add files") and the attachment dialog opens on the places to add from: choose, drop or paste a file, or add a link under Link (URL). Before uploading, the dialog checks the field's maxFiles (default 20), maxSize (default 25 MB) and accept, and lists each refused file with its name and the reason: "At most 1 file", "Larger than 10 MB", "Not an accepted type". A file added by URL gets the maxFiles and accept checks; its type comes from the name's extension, so with accept: '.pdf,.doc,.docx' a link to cv.pdf is taken and a link with no extension is refused. A file that fails to upload stays in the dialog with Retry. The upload runs when the file is added, not when the form is sent, and Done waits for uploads still running.

An uploader for one column only goes in that column's fieldProps.upload; it wins over the app-wide one. Both get the file, an abort signal (aborted when the candidate removes the file or cancels the dialog), onProgress, the column id and row, which in a form is what the fields show so far, with no record id yet.

7. Check it again on the server

The form's checks help a person filling it in, and formRequired is one of them: nothing on a server knows of it. A table served by createBaseEndpoint is checked only if you pass validate or hooks (how). Anyone can post to /apply without the form, so the endpoint checks every field again with the same linkHref the form uses for email, URL and phone, keeps only the fields a candidate may set, and sets the team's fields itself:

// src/routes/apply/+server.ts
import { error, json } from '@sveltejs/kit'
import { linkHref } from '@svgrid/enterprise/base'
import { SOURCES } from '$lib/hiring'
import { automations } from '$lib/server/automations'

declare const db: {
  roleIsOpen: (id: string) => Promise<boolean>
  insertCandidate: (row: Record<string, unknown>) => Promise<string>
}

// Where the upload endpoint in step 6 stores resumes.
const FILES = 'https://files.example.com/resumes/'

export async function POST({ request }: { request: Request }) {
  const body = (await request.json()) as Record<string, unknown>
  const text = (k: string, max = 200) => {
    const v = body[k]
    return typeof v === 'string' ? v.trim().slice(0, max) : ''
  }

  const name = text('name')
  if (!name) error(400, 'Candidate is required')
  const email = text('email')
  if (!linkHref('email', email)) error(400, 'Not a valid email address')
  const phone = text('phone', 40)
  if (phone && !linkHref('phone', phone)) error(400, 'Not a valid phone number')
  const portfolio = text('portfolio', 500)
  if (portfolio && !linkHref('url', portfolio)) error(400, 'Not a valid web address')

  const role = Array.isArray(body.role) ? String(body.role[0] ?? '') : ''
  if (!(await db.roleIsOpen(role))) error(400, 'Pick an open role')

  const resume = Array.isArray(body.resume) ? body.resume.slice(0, 1) : []
  if (!resume.length || !resume.every((a) => typeof a?.url === 'string' && a.url.startsWith(FILES))) error(400, 'Upload a resume')

  const years = body.years == null ? null : Number(body.years)
  if (years != null && !(Number.isInteger(years) && years >= 0 && years <= 60)) error(400, 'Years is not a whole number')

  const start = text('start', 10)
  if (start && !/^\d{4}-\d{2}-\d{2}$/.test(start)) error(400, 'Earliest start is not a date')

  const source = SOURCES.some((s) => s.value === body.source) ? body.source : 'Careers page'

  const id = await db.insertCandidate({
    name, email, phone, role: [role], resume, portfolio, years, start, source,
    notes: text('notes', 5000),
    // Never from the request: these belong to the team.
    stage: 'Applied', recruiter: null, applied: new Date().toISOString(),
  })
  // Step 8: the "A form is sent" automations that run on the server.
  await automations.formSubmitted('candidates', id, 'apply')
  return json({ id })
}

The form shows the error() message only if send passes it on; the one in step 4 shows its own line for any failure.

To see new applications in the base without a reload, give the Candidates table a source with realtime: Keep a base in a database.

8. Run an automation when a form is sent

In the Automations dialog the trigger is "A form is sent", with a Form picker: "Any form of this table" or one form view. In code it is formSubmitted, and view names the form:

import type { BaseAutomation } from '@svgrid/enterprise/base'

export const candidateAutomations: BaseAutomation[] = [
  {
    id: 'new-application',
    name: 'Announce a new application',
    enabled: true,
    trigger: { type: 'formSubmitted', view: 'apply' },
    actions: [{ type: 'notify', message: 'New application from {Candidate}', severity: 'info' }],
  },
  {
    id: 'thank-you-email',
    name: 'Thank the candidate',
    enabled: true,
    runOn: 'server',
    trigger: { type: 'formSubmitted', view: 'apply' },
    actions: [
      {
        type: 'email',
        to: '{Email}',
        subject: 'We got your application',
        body: 'Hi {Candidate}, thank you for applying. We reply within a week.',
      },
    ],
  },
]

Put them on the table (automations: candidateAutomations). A form on its own needs one <SvToaster /> from @svgrid/grid for the notice; inside a base it shows without one. In the base, a form view sends its record to the table's automations with the view's id. They need <SvBase tables>: with data and columns a form still adds records, but no automation runs.

The public page has no base and no browser runner, so the endpoint in step 7 tells the automation server after the insert. The view id there is whatever string your automations name. Only automations with runOn: 'server' run on the server. If it has not seen the record yet, it reads the table again first, and that reading also runs the table's "A record is created" server automations for the new record.

Show a field only for some answers

Open the live example: Form logic and prefilled links (Base)

In the demo, pick Bug as the Topic and App version appears; switch to Billing and it gives way to Invoice number. The buttons on the right open the form from prefilled links.

A field can wait for an answer before it shows. conditions maps a column id to a view bar filter over the other answers, the same FieldFilter the Filter button saves. On a form view the key is formConditions:

import type { FieldFilter } from '@svgrid/enterprise/base'

const is = (column: string, value: string): FieldFilter => ({
  kind: 'fieldFilter',
  conjunction: 'and',
  conditions: [{ column, kind: 'select', op: 'is', value }],
})

const apply = {
  id: 'apply',
  name: 'Apply',
  type: 'form',
  formFields: ['name', 'email', 'employment', 'company', 'reason', 'otherReason'],
  formRequired: ['name', 'email', 'company', 'otherReason'],
  formConditions: {
    company: is('employment', 'Employed'),
    otherReason: is('reason', 'Other'),
  },
}

With SvBaseForm it is conditions={{ company: is('employment', 'Employed') }}.

The form checks the conditions each time an answer changes. While a field's condition does not hold:

When the field shows again it starts with the value a new record gets. A condition reads the answers by column id; a field the form does not ask for is read as the new record would have it.

prefill fills fields from a link, the convention people already paste into emails: ?prefill_<Field name>=value. The name is the field's header or its column id, URL-encoded. hide_<Field name>=true keeps a filled field out of sight and still sends it:

https://example.com/apply?prefill_Role=Product%20designer&prefill_Source=Referral&hide_Role=true

On a form view, formPrefill: true reads the page's own URL. On a page, pass it to SvBaseForm:

<SvBaseForm {api} fields={APPLY_FIELDS} prefill />
<SvBaseForm {api} fields={APPLY_FIELDS} prefill={page.url.searchParams} />
<SvBaseForm {api} fields={APPLY_FIELDS} prefill={{ Role: 'r2', Source: 'Referral' }} />

prefill takes true (the page's URL, nothing during a server render), a URL or query string, URLSearchParams, or values by field name or column id. When it changes to other answers, the form starts a new record.

Each value is read the way a pasted cell is:

Field type prefill_ value
text, email, URL, phone As written
number, currency, percent The number as typed, 1,200 included; text that is no number is dropped
checkbox true, 1, yes, on check it; anything else unchecks it
date 2026-11-02
single select An option's value or label, any case
multiple select Values or labels, comma-separated
user A person's id, name or email
link Record ids or names, comma-separated

An option the select does not have, a person nobody is, or a record that does not exist is dropped: a link never adds an option. Files and computed fields cannot be filled. A link's value goes over the field's default. hide_ works only on a field the link filled; if a hidden value fails a check on Submit, the field shows with its message.

formPrefillLink builds such a link from values by column id:

import { formPrefillLink } from '@svgrid/enterprise/base'

formPrefillLink('https://example.com/apply', { role: ['r2'], source: 'Referral' }, candidateColumns, { hide: ['role'] })
// https://example.com/apply?prefill_Role=r2&prefill_Source=Referral&hide_Role=true

With the columns, each parameter carries the field's header. A list is joined with commas, a Date written as YYYY-MM-DD, and the base URL's own query and #hash are kept.

The link is typed by whoever sends it. On a public form, say which fields a link may fill: prefillFields on SvBaseForm, or a list for formPrefill on a form view. A prefill_ or hide_ for any other field is ignored, so a link cannot set the Source or the Owner you meant to fill yourself:

import type { FieldView } from '@svgrid/enterprise/base'

const apply: FieldView = {
  id: 'apply',
  name: 'Apply',
  type: 'form',
  formFields: ['name', 'email', 'role', 'source'],
  // A link may pick the role and say where the candidate came from, nothing else.
  formPrefill: ['Role', 'source'],
  formFooter: 'We keep your answers for 12 months. Write to [email protected] to have them removed.',
}

Check every value on the server as in step 7 all the same.

formFooter on a form view is a line of plain text under the submit button: who reads the answers, how long they are kept. For more than a line (a logo, links to your terms), give <SvBase> a formFooter snippet; it gets the form view, so one snippet can serve every form:

<SvBase bind:tables editable>
  {#snippet formFooter(view)}
    <p>By sending {view.name.toLowerCase()} you agree to our <a href="/terms">terms</a>.</p>
  {/snippet}
</SvBase>

On a page of your own, SvBaseForm takes the same as footerText and a footer snippet.

One question at a time

layout="steps" asks one question at a time, as a conversation: a progress bar, "Question 2 of 6", Back and Next. Each answer is checked before the next question comes (a required field left empty, or an e-mail that is not one, stays with its message). Enter after an answer goes on, and on the last question sends the form. Shift+Enter, or Enter in a long text, starts a new line. A send that finds a problem goes back to the question it is on.

The next question slides in from the side it is on (transition="slide"), fades in ("fade") or just appears ("none"). A visitor who asks the system for less motion gets none, whatever the form says.

<SvBaseForm {api} fields={['name', 'email', 'role', 'note']} required={['name', 'email']}
  layout="steps" transition="slide" title="Apply" />

Conditions work as in the list: a question whose condition fails is skipped, and the count follows.

Suggest answers before it is sent

A help desk's request form can show the help articles that may already answer the question, before anyone sends it. setFormSuggestions gives every form that: once the first text field (the subject) holds a few words, list is asked with the table, that text and the answers so far, and up to five suggestions show under the field. Each opens in place; This solved it calls solved and ends the form with nothing added, and Ask something else starts again.

import { setFormSuggestions } from '@svgrid/enterprise/base'

setFormSuggestions({
  list: async (tableId, text) => {
    const res = await fetch(`/articles?q=${encodeURIComponent(text)}`)
    return (await res.json()) as Array<{ id: string; title: string; text: string }>
  },
  solved: (tableId, id) => {
    void fetch(`/articles/${id}/solved`, { method: 'POST' })
  },
})

A text field takes its value when it is left (Tab, Enter, or a click elsewhere), so the suggestions come then, not on every key.

SvBaseForm props

Prop Type Default What it does
api grid api required The api of the grid the record is added to, from its onApiReady. Nothing draws until that grid has drawn once.
fields ReadonlyArray<string> every field a person can fill in Column ids, in order. An id that is not such a field is skipped.
required ReadonlyArray<string> [] Column ids that must have a value before the record is added.
title string 'New record' The heading.
description string '' The line under the heading.
submitLabel string 'Submit' The button's text.
defaults () => Record<string, unknown> Values each record from this form starts with. The grid's rowAdder.defaults() wins over them. Called once per record. <SvBase tables> passes one that gives an id.
conditions Record<string, FieldFilter> Column id -> when that field shows. A hidden field is not required, not checked and not sent (Show a field only for some answers).
prefill boolean | string | URLSearchParams | Record<string, unknown> (FormPrefill) Answers to start with: true reads the page's URL, a string or URLSearchParams is read for prefill_ and hide_, an object gives values by field name or column id (Fill the form from a link).
prefillFields ReadonlyArray<string> every field asked for The fields prefill may fill or hide, by field name or column id.
footerText string A line under the submit button.
labels Record<string, string> Column id -> the question this form asks for that field, in place of the field's name. The required message uses it too.
help Record<string, string> Column id -> the help under that field on this form, in place of its description. An empty string shows none.
footer Snippet What goes under the submit button, after footerText.
layout 'list' | 'steps' 'list' steps asks one question at a time, with Back and Next (One question at a time).
transition 'slide' | 'fade' | 'none' 'slide' How the next question comes in, with layout="steps". None for visitors who ask for less motion.
onSubmit (row: Record<string, unknown>) => void | Promise<unknown> Called after the row was appended to the grid and the grid's onRowAdd ran. A Promise keeps the button disabled until it settles: resolved shows "Thank you", rejected takes the row back out of the grid, keeps the fields and shows the error's message.

Form view keys

Key Read as
type 'form'
name The view's name in the menu; the heading when there is no formTitle
formFields The fields it asks for, in order
formTitle The heading
formDescription The line under it
formRequired Column ids that must have a value, as required on SvBaseForm
formSubmitLabel The button's text (default 'Submit')
formConditions Column id -> when that field shows, as conditions on SvBaseForm
formPrefill true fills fields from the page's URL, as prefill on SvBaseForm; a list of field names or column ids lets the link fill only those
formFooter A line of plain text under the submit button
formLabels Column id -> the question asked for that field, as labels on SvBaseForm
formHelp Column id -> the help under that field, as help on SvBaseForm

A record the view sends reaches onRowAdd, onTablesChange and the formSubmitted automations, which get the view's id.

What a screen reader and a browser get

A field that takes typed text (text, long text, number, email, URL, phone) is a real <input> or <textarea> with a <label> from the start, and a checkbox a real checkbox. A required field has aria-required. Fields with a picker (a select, a date, a file, a link) are a labelled button until opened, and their name says when they are required.

A field in error gets aria-invalid and its message through aria-describedby. A submit that fails says how many fields need attention, and focus goes to the first of them.

Email, phone and URL fields carry their autocomplete purpose, so a browser can fill them in. A text field gets one from an English name (Name, First name, Last name, Company, Address, City, Zip, Country). For any other name or language, set it on the field:

{ field: 'nombre', header: 'Nombre', fieldType: 'text', fieldProps: { autocomplete: 'name' } }

What the form checks

A failed check shows its message under the field and nothing is sent. The message goes away when that field gets a new value.

Pitfalls

Next

Live examples

  • Hiring tracker - A hiring tracker, ready to use: Candidates and Roles as two linked tables. Candidates have photo, role, stage, recruiter, rating, interview date and resume; each role lists its candidates. Views for the pipeline as a Kanban, all candidates, a gallery of faces, interviews and an application form.
  • Form logic and prefilled links - A support form whose fields follow the answers: Company size for a business account, App version for a bug, Invoice number for billing, What is blocked when the request blocks work. A hidden field is not required and not sent. Prefilled links fill answers from the URL, and hide_ keeps a filled field out of sight.

Related articles