Open MercatoDocsSearch docsAPI reference

Framework

Admin forms with CrudForm

Use CrudForm when a record needs a create or edit screen with consistent validation and navigation. Define the fields once, then decide which values to load, which to send and how the operator sees a rejected submission.

A lightweight, extensible form component for admin CRUD pages. It supports validation via Zod, mobile-first fullscreen UX, inline help, a header with back navigation, and richer editors like tags, rich text, and relations. You can also embed fully custom React components per field.

Basic usage

import { CrudForm, type CrudField } from '@open-mercato/ui/backend/CrudForm'
import { z } from 'zod'

const schema = z.object({
  title: z.string().min(1, 'Title is required'),
  is_done: z.boolean().optional(),
})

const fields: CrudField[] = [
  { id: 'title', label: 'Title', type: 'text', required: true, description: 'A clear summary of the task' },
  { id: 'is_done', label: 'Done', type: 'checkbox' },
]

<CrudForm
  title="Create Todo"
  backHref="/backend/todos"
  schema={schema}
  fields={fields}
  submitLabel="Create"
  cancelHref="/backend/todos"
  successRedirect="/backend/todos"
  onSubmit={async (values) => { /* ... */ }}
/>

Props

Field types

Built-in type values:

Common field properties:

Select/relation properties:

Custom field renderer

Use type: 'custom' to embed your own React component:

const fields: CrudField[] = [
  {
    id: 'assignee',
    label: 'Assignee',
    type: 'custom',
    component: ({ value, setValue, error, autoFocus }) => (
      <MyUserPicker value={value} onChange={setValue} autoFocus={autoFocus} error={error} />
    ),
  },
]

The component receives { id, value, setValue, error, autoFocus }.

Grouped layout (two columns)

import type { CrudFormGroup } from '@open-mercato/ui/backend/CrudForm'

const groups: CrudFormGroup[] = [
  { id: 'details', title: 'Details', column: 1, fields: ['title'] },
  { id: 'status', title: 'Status', column: 2, fields: ['is_done'] },
  { id: 'attributes', title: 'Attributes', column: 2, kind: 'customFields' },
  {
    id: 'info',
    title: 'Info',
    column: 2,
    component: ({ values }) => <pre className="text-xs">{JSON.stringify(values, null, 2)}</pre>,
  },
]

<CrudForm
  entityId="example:todo"
  fields={[ /* base fields */ ]}
  groups={groups}
  onDelete={async () => {
    // await DELETE; then redirect with flash message
    router.push('/backend/todos?flash=' + encodeURIComponent('Record has been removed') + '&type=success')
  }}
/>

Behavior:

Hiding groups by id

To render a built-in form without some of its cards, pass hiddenGroupIds instead of copying the page or rebuilding the groups array:

<CrudForm
  fields={createCompanyFormFields(t)}
  groups={createCompanyFormGroups(t)}
  hiddenGroupIds={['profile', 'customFields']}
  onSubmit={handleSubmit}
/>

Behavior:

Caution · Hiding is presentation-only

Fields that live only in a hidden group keep their values and are still submitted unchanged, so hiding a group can never clear the underlying columns. A required field that lives only in a hidden group is skipped by the built-in required check (the same way visibleWhen works), but a host-supplied Zod schema is not bypassed – do not hide a group whose fields the schema requires unless defaults supply them.

Caution · Hiding a widget card does not disable the widget

An injected widget's handlers belong to the injection spot, not to its card. Hiding a widget:<widgetId> group therefore removes the card while onBeforeSave and transformFormData keep running, and the widget's fields stay required – so a validation failure can block save with nothing on screen to fix. Do not hide a widget group that gates saving; disable the widget instead.

Because hosts address groups by id, a built-in group's id is a contract surface: see BACKWARD_COMPATIBILITY.md before renaming one, and pin a builder's ids with a guard test.

Mobile UX

Validation

Provide a Zod schema via schema. Field-level errors are displayed under each field; a general form error (from onSubmit) shows above actions.

Custom fields rules:

Rules live in the field definition JSON under validation:

validation: [
  { rule: 'required', message: 'Required' },
  { rule: 'integer', message: 'Must be integer' },
  { rule: 'gte', param: 1, message: '>= 1' },
  { rule: 'lte', param: 5, message: '<= 5' },
]

Notes

Custom field text

Stored custom-field labels, descriptions, fieldset labels, and group text render literally by default. A form can opt into translation with resolveCustomFieldText?: (text: string, context: { entityId: string; path: string }) => string. The callback changes display text only; definition keys and submitted values stay unchanged.

The context identifies the owning entity and metadata location:

MetadataPath
Field label or descriptionfields.<fieldKey>.label / fields.<fieldKey>.description
Field group title or hintfields.<fieldKey>.group.title / fields.<fieldKey>.group.hint
Fieldset label or descriptionfieldsets.<fieldsetCode>.label / fieldsets.<fieldsetCode>.description
Fieldset group title or hintfieldsets.<fieldsetCode>.groups.<groupCode>.title / fieldsets.<fieldsetCode>.groups.<groupCode>.hint

Keep module-specific defaults and namespaced translation keys in the owning module. Translate only recognized metadata whose stored text still matches its seeded default, return customized or unknown text unchanged, and pass the stored text as the translator fallback. Memoize the resolver with the current translator as a dependency so locale changes update the same mounted form.

Custom Fields → Editors and Inputs

When entityId is provided, custom fields are fetched from /api/entities/definitions and rendered automatically:

Declare these hints via the DSL in your module:

defineFields(E.example.todo, [
  cf.text('labels', { label: 'Labels', multi: true, input: 'tags' }),
  cf.multiline('description', { label: 'Description', editor: 'markdown' }),
])

## Custom Fields → Visibility
Custom field visibility is controlled per field via `custom_field_defs.config_json` and affects forms, filters, and list pages:

- `formEditable` (default true): include the field in CrudForm when `entityId` is provided.
- `filterable` (default false): include the field in DataTable filter overlays.
- `listVisible` (default true): show the field as a column in generic records lists.

You can edit these flags in the admin under Backend → Custom Fields → Definitions. For programmatic control, set them in your DSL or seeding CLI.

To apply list visibility to a table, fetch definitions and filter columns via helper:

```ts
import { fetchCustomFieldDefs } from '@open-mercato/ui/backend/utils/customFieldDefs'
import { applyCustomFieldVisibility } from '@open-mercato/ui/backend/utils/customFieldColumns'

const defs = await fetchCustomFieldDefs('example:todo')
const visibleColumns = applyCustomFieldVisibility(columns, defs)
New kinds can be registered via a field registry. For example, the `attachments` kind ships with an input that lets users upload files related to a record.

Attachments field:
- Kind: `attachment`
- UI: file input + list of uploaded files (after the record is saved)
- Definition editor options: `maxAttachmentSizeMb`, `acceptExtensions` (e.g. `['pdf','png']`)
- Upload API: `POST /api/attachments`
- List API: `GET /api/attachments?entityId=...&recordId=...`

Next: Custom field validation