Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

21.9 KB
Raw Blame
---
title: "Custom Fields"
sidebarTitle: "Custom Fields"
description: "Add fields, detail rows, section actions, and list columns to a built-in model."
---

Custom fields extend a built-in model's forms, detail sections, and list table
without forking the page. You add a field to the create and edit forms, a row to
the detail view, an action to a section menu, or a column to the list.

You write one file per model under `src/custom-fields/` and default-export a
`defineCustomFieldsConfig`. The config targets a model, optionally fetches linked
module data alongside it, and describes what to add to each surface.

## Add a custom field

<Steps>
  <Step title="Create a custom-fields file">
    Create a file under `src/custom-fields/` and default-export
    `defineCustomFieldsConfig` with the model you want to extend. Start with
    `product`.

    ```tsx apps/vendor/src/custom-fields/product.tsx
    import { defineCustomFieldsConfig } from "@mercurjs/dashboard-sdk"

    export default defineCustomFieldsConfig({
      model: "product",
    })
    ```
  </Step>

  <Step title="Describe the field with `createFormHelper`">
    Import `createFormHelper` from `@mercurjs/dashboard-shared` and turn a Zod
    schema into an input type and validation. The Zod schema drives both the
    default input and the validation.

    ```tsx apps/vendor/src/custom-fields/product.tsx
    import { createFormHelper } from "@mercurjs/dashboard-shared"

    type ProductWithMeta = { metadata?: Record<string, unknown> }
    const form = createFormHelper<ProductWithMeta>()
    ```
  </Step>

  <Step title="Add the field to a form">
    Add the field to a built-in form zone and tab. This injects an `ERP ID` field
    into the product edit form.

    ```tsx apps/vendor/src/custom-fields/product.tsx
    export default defineCustomFieldsConfig({
      model: "product",
      forms: [
        {
          zone: "edit",
          tab: "general",
          fields: {
            erp_id: form.define({
              validation: form.string().nullish(),
              defaultValue: (data) => (data?.metadata?.erp_id as string) ?? "",
              label: "ERP ID",
              placeholder: "ERP-000",
            }),
          },
        },
      ],
    })
    ```
  </Step>

  <Step title="Run the panel">
    Start the panel and open the product edit form. The field renders in its tab.

    ```bash Terminal
    bun run dev
    ```

    For `product`, values submit under `additional_data` and persist onto the
    product's `metadata`. See [Persistence](#persistence) for other models.
  </Step>
</Steps>

## Configuration

`defineCustomFieldsConfig` takes one object.

| Field      | Type                   | Description                                                                                          |
| ---------- | ---------------------- | --------------------------------------------------------------------------------------------------- |
| `model`    | `CustomFieldModel`     | Target model. Start with `"product"`. Typed against `CustomFieldsRegistry`.                          |
| `link`     | `string \| string[]`   | Module link or links fetched alongside the entity. Their data is available to columns and displays. |
| `forms`    | `CustomFormEntry[]`    | Fields injected into built-in create, edit, and onboarding forms.                                   |
| `displays` | `CustomDisplayEntry[]` | Field replace, remove, or add, plus `ActionMenu` actions on detail sections.                        |
| `list`     | `CustomListExtension \| CustomListExtension[]` | Columns, bulk actions, filters, and view defaults on the model's tables. |

## Add fields to a form

Inject fields into a built-in create, edit, or onboarding form.

```tsx
forms: [
  {
    zone: "edit",         // "create" | "edit" | "organize" | "attributes" | "onboarding"
    tab: "general",       // TabbedForm tab id, or wizard step id for zone: "onboarding"
    fields: {
      erp_id: form.define({
        validation: form.string().nullish(),
        defaultValue: (data) => (data?.metadata?.erp_id as string) ?? "",
        label: "ERP ID",
        description: "External system identifier",
        placeholder: "ERP-000",
        component: MyErpInput,
      }),
    },
  },
]
```

Each field is a `CustomFormField`.

| Field          | Type                             | Description                                                    |
| -------------- | -------------------------------- | ------------------------------------------------------------- |
| `validation`   | Zod schema                       | Drives both the default input type and validation.            |
| `defaultValue` | `unknown \| ((data) => unknown)` | Static value or a resolver from the loaded entity.            |
| `label`        | `string` (optional)              | Field label.                                                  |
| `description`  | `string` (optional)              | Help text below the input.                                    |
| `placeholder`  | `string` (optional)              | Input placeholder.                                            |
| `type`         | `"text" \| "number" \| "boolean" \| "select"` (optional) | Input kind. Defaults to the Zod type. Data grids use it to pick the cell. |
| `options`      | `{ label: string; value: string }[]` (optional) | Choices for `type: "select"`.                        |
| `component`    | `ComponentType<{ field?, data? }>` (optional) | Custom render. Falls back to a default input for the type. |

<Warning>
  **A form-field `component` renders inside the `Form.Field` chain.** It receives
  `field` (the bound `name`, `value`, `onChange`, and `onBlur`) and `data` (the
  loaded entity). Values live in form state under `additional_data`. For
  `product`, custom fields persist onto the product's `metadata`.
</Warning>

### Replace or hide a built-in field

A `fields` key that matches one of the form's own fields overrides it instead of
adding a new one. `null` hides the field. A field definition replaces how it
renders, and the replacement still writes to the built-in form key.

```tsx
forms: [
  {
    zone: "edit",
    fields: {
      leadtime_to_ship: null,                                   // hide
      sku: form.define({ validation: form.string(), component: SkuInput }), // replace
    },
  },
]
```

The overridable field ids are typed per model and autocomplete in your editor.
Validation of a built-in field stays the built-in schema's. A hidden field keeps
its default value, so hide a required field only when that default is valid.

### Fields in tabbed create forms

In a tabbed create form, set `tab` to place a field on a tab. A field without a
`tab` renders on the first tab. Continue validates the custom fields of the tab
you leave, and Publish validates them all.

```tsx
forms: [
  { zone: "create", tab: "organize", fields: { season: form.define({ validation: form.string().optional(), label: "Season" }) } },
  { zone: "create", fields: { erp_id: form.define({ validation: form.string(), label: "ERP ID" }) } }, // first tab
]
```

The product create form has the tabs `details`, `organize`, `attributes`, and
`variants`. Product-level values reach the `productsCreated` hook of
`createProductsWorkflow` as `additional_data`.

### Add columns to a spreadsheet tab

Some forms are spreadsheets, such as the product create form's `variants` tab or
the offer create form's `stockLevelsAndPrices` tab. Target the tab and the same
rules apply to its columns: a built-in column id with `null` hides it, a
definition replaces it, and any other key adds an editable column. Added values
are stored per row under `additional_data`. A spreadsheet tab only takes fields
that name it in `tab`; untabbed fields never become columns.

```tsx
forms: [
  {
    zone: "create",
    tab: "stockLevelsAndPrices",
    fields: {
      condition: null,
      warranty_months: form.define({
        validation: form.number().optional(),
        label: "Warranty (months)",
      }),
    },
  },
]
```

Each row's values reach a workflow hook, keyed by the id of the record the row
created or updated. Persist them from the hook.

| Model     | Zone and tab                        | Spreadsheet                                  | Added columns reach                                                             |
| --------- | ----------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------- |
| `product` | `create`, tab `variants`            | Product create variants (admin and vendor)   | `createProductsWorkflow` → `productsCreated` as `variants_additional_data`     |
| `offer`   | `create`, tab `stockLevelsAndPrices` | Offer create stock and prices (vendor)       | `createOffersWorkflow` → `offersCreated` as `offers_additional_data`           |
| `offer`   | `edit-price`                        | Offer prices for a product (vendor)          | `updateOffersWorkflow` → `offersUpdated` as `additional_data`, one call per offer |
| `offer`   | `edit-stock`                        | Offer stock levels for a product (vendor)    | Not supported: hide and replace only                                            |
| `offer`   | `pricing`                           | Offer price tiers (vendor)                   | Not supported: hide and replace only                                            |
| `offer`   | `inventory-batch`                   | Offer inventory items by location (vendor)   | Not supported: hide and replace only                                            |

A replaced spreadsheet column with a `component` is read-only and receives the
row as `data`. Without a `component`, it keeps editing the built-in value with the
cell for its `type`.

## Customize the onboarding wizard

The vendor onboarding wizard is the `onboarding` form zone of the `seller` model. Each step is a `tab`. Use the same `forms` entries to add fields to a step, add a step, remove a step, or reorder the steps.

```tsx apps/vendor/src/custom-fields/seller.tsx
import { defineCustomFieldsConfig } from "@mercurjs/dashboard-sdk"
import { createFormHelper } from "@mercurjs/dashboard-shared"

const form = createFormHelper()

export default defineCustomFieldsConfig({
  model: "seller",
  forms: [
    // Add fields to a built-in step
    { zone: "onboarding", tab: "address", fields: { region_note: form.define({ validation: form.string().optional() }) } },
    // An unknown tab becomes a new step
    {
      zone: "onboarding",
      tab: "documents",
      label: "Documents",
      rank: 25,
      optional: true,
      fields: {
        vat_document_url: form.define({ validation: form.string().url(), label: "VAT document URL" }),
      },
    },
    // Remove a built-in step
    { zone: "onboarding", tab: "company", disabled: true },
  ],
})
```

| Option     | Type      | Description                                                                                       |
| ---------- | --------- | ------------------------------------------------------------------------------------------------- |
| `label`    | `string`  | Step heading. Set it on every new step.                                                           |
| `rank`     | `number`  | Sort position. New steps without a rank go last. Also reorders a built-in step.                   |
| `optional` | `boolean` | Shows a **Skip** button. Set `false` on a built-in step to hide its Skip button.                  |
| `disabled` | `true`    | Removes a built-in step. Takes no `fields`. The `store` step can't be removed.                    |

The built-in steps and their defaults:

| Step      | `rank` | `optional` |
| --------- | ------ | ---------- |
| `store`   | 10     | `false`    |
| `address` | 20     | `true`     |
| `company` | 30     | `true`     |
| `payment` | 40     | `true`     |

The last step's button reads **Finish** and creates the seller. Values from every step's custom fields are merged into one `additional_data` object on `POST /vendor/sellers`, which reaches the `sellerAccountCreated` hook of `createSellerAccountWorkflow`. A skipped step contributes nothing, even if its fields are required.

<Note>
  Always set `tab` on an onboarding entry. An entry without a `tab` renders its fields on every step.
</Note>

## Extend detail sections

Add, replace, or remove fields on a detail section, and add actions to its
`ActionMenu`.

```tsx
displays: [
  {
    zone: "general", // an existing detail section id
    fields: [
      { id: "erp_id", component: ErpRow },             // ADD (unknown id -> new row)
      { id: "status", component: BrandedStatusBadge }, // REPLACE a built-in field
      { id: "created_by", component: null },           // REMOVE a built-in field
    ],
    actions: [
      { rank: 0, component: SyncErpAction },            // add to the section's ActionMenu
    ],
  },
]
```

`fields[]` is `CustomDisplayField`.

| Field       | Type                               | Description                                                                            |
| ----------- | ---------------------------------- | -------------------------------------------------------------------------------------- |
| `id`        | `displayFieldIds \| (string & {})` | Built-in field id, which autocompletes, to replace or remove. Any other string adds a new row. |
| `component` | `ComponentType<{ data? }> \| null` | Render component, or `null` to remove a built-in field.                                |

A display `component` receives the loaded detail entity as `data`, including any
`link`ed module data. If the config declares `link: "brand"`, read it off
`data.brand`.

```tsx
const BrandRow = ({ data }: { data?: { brand?: { name: string } } }) => (
  <Text>{data?.brand?.name}</Text>
)
```

`actions[]` is `SectionAction`, the same shape as list `bulkActions`.

| Field       | Type                       | Description                                              |
| ----------- | -------------------------- | ------------------------------------------------------- |
| `rank`      | `number` (optional)        | Position within the section's `ActionMenu`.             |
| `component` | `ComponentType<{ data? }>` | Owns its own label, icon, group placement, and `onClick`. |

## Extend the list table

Override or add columns, register bulk actions and filters, and set view defaults
on the model's list table.

```tsx
list: {
  columns: [
    { id: "title", component: ({ value }) => <strong>{value}</strong> },            // override a cell
    { id: "brand_name", header: "Brand", component: ({ row }) => row.brand?.name },  // add from link
  ],
  bulkActions: [{ rank: 0, component: ArchiveBulkAction }],
  filters: [
    { key: "customer_id", label: "Buyer email", type: "select", options: buyerEmails, searchable: true }, // replace a built-in filter
    { key: "status", remove: true },                                                                     // remove a built-in filter
    { key: "erp_synced", label: "Synced to ERP", type: "select", options: yesNo },                       // add a new one
  ],
  viewDefaults: {
    columnVisibility: { created_at: false },
    columnOrder: ["title", "sku", "erp_id"],
  },
}
```

`columns[]` is `CustomColumn`.

| Field       | Type                                         | Description                                                          |
| ----------- | -------------------------------------------- | ------------------------------------------------------------------- |
| `id`        | `string`                                     | Column id. Matches a built-in column to override, or adds a new one. |
| `header`    | `string` (optional)                          | Column header text, for added columns.                              |
| `component` | `ComponentType<{ row?, value? }>` (optional) | Cell renderer. Receives the full `row` and the cell `value`.        |

`filters[]` is `CustomListFilter`. The `key` is the query param the filter
writes, so it matches a built-in filter by its param name (`customer_id`,
`status`, `created_at`, ...).

| Field     | Type                                                  | Description                                                                                   |
| --------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `key`     | `string`                                              | Built-in filter key to replace or remove. Any other string adds a new filter.                 |
| `remove`  | `true` (optional)                                     | Drop the built-in filter with this `key`. No other fields are needed.                         |
| `label`   | `string`                                              | Label shown in the "Add filter" menu.                                                         |
| `type`    | `"select" \| "string" \| "number" \| "date"`          | Filter control.                                                                               |
| `options` | `{ label: string; value: unknown }[]`                 | Choices for a `select` filter. `multiple` and `searchable` are also accepted.                 |

A replacement keeps the built-in filter's position; added filters go after the
built-in ones.

### Extend other tables of the model

A `list` block without a `zone` targets the model's list page. Other tables of
the same model, such as a detail-page section or a picker inside a create form,
have their own `zone`. Pass an array to extend several tables. The zones and
column ids are typed per model.

```tsx
list: [
  { columns: [{ id: "brand_name", header: "Brand", component: BrandCell }] },
  {
    zone: "variants",
    columns: [{ id: "sku", component: SkuCell }],
    viewDefaults: { columnVisibility: { inventory: false } },
  },
]
```

| Model   | Zone               | Table                                       |
| ------- | ------------------ | ------------------------------------------- |
| `offer` | `list`             | Offer list (admin and vendor)               |
| `offer` | `variants`         | Offer detail variants table (admin and vendor) |
| `offer` | `inventory`        | Inventory items of an offer variant (admin and vendor) |
| `offer` | `create-catalogue` | Product picker in the offer create form (vendor) |
| `inventory_item` | `location-levels` | Inventory item detail location levels (admin and vendor) |
| `reservation` | `inventory-item` | Inventory item detail reservations (admin and vendor) |
| `product` | `variants` | Product detail variants table (admin and vendor) |
| `collection` | `products` | Collection detail products table (admin and vendor) |
| `category` | `products` | Category detail products table (admin and vendor) |

Every table keeps its row selection checkbox as the first column and its row
actions menu as the last; extensions add and reorder columns between them.

<Note>
  **Bulk-action rendering is deferred in the MVP.** `bulkActions` are accepted and
  surfaced by the config, but not yet mounted into the list toolbar.
</Note>

<Warning>
  **The vendor product list is field-constrained.** It must use the curated fields
  from `useProductTableQuery`. The SDK merges `link` fetches with the `+` and `-`
  convention, never bare fields, or the list returns a 500. You never hand-write
  the field list. The `link` declaration drives it.
</Warning>

## Combine configs from plugins and your app

Every config for a model applies in order: installed plugins first, then your
app's `src/custom-fields/` files. A later config sees everything earlier configs
added, not only the built-ins, so your app can change what a plugin contributed.

| Contribution          | Matched by | A later config with the same id/key                                        |
| --------------------- | ---------- | -------------------------------------------------------------------------- |
| `list.columns`        | `id`       | Replaces the column in place. Hide it with `columnVisibility: { id: false }`. |
| `list.filters`        | `key`      | Replaces the filter in place, or drops it with `remove: true`.              |
| `displays[].fields`   | `id`       | Replaces the field in place, or drops it with `component: null`.            |
| `forms[].fields`      | field name | Replaces the field, including its `zone` and `tab`.                         |
| `columnVisibility`    | column id  | Overrides the earlier value for that column.                                |
| `columnOrder`         | n/a        | Replaces the earlier order.                                                 |

`link`, `bulkActions`, display `actions`, `activity`, and `actionLocks` add up
across configs.

```tsx
// src/custom-fields/product-brand.tsx: rework the plugin's "brand" column
export default defineCustomFieldsConfig({
  model: "product",
  link: "brand",
  list: {
    columns: [{ id: "brand", header: "Maker", component: ({ row }) => row.brand?.name }],
    filters: [{ key: "brand_id", remove: true }],
  },
})
```

## Fetch linked module data

Declare `link` to fetch a module link alongside the entity. Its data rides on the
`data` passed to displays and on the `row` passed to columns.

```tsx
export default defineCustomFieldsConfig({
  model: "product",
  link: "brand", // string | string[]
  displays: [/* read data.brand here */],
  list: {/* read row.brand here */},
})
```

## Persistence

<Warning>
  **The MVP is a UI surface only.** Custom fields render, validate, and display
  through the built-in forms, sections, and tables. There is no generic core-side
  write path. For `product`, values submit under `additional_data` and persist
  onto `metadata`. To store data for other models, wire your own route or
  workflow, or use the backend
  [Custom Fields module](/rc/resources/customization/custom-fields).
</Warning>

## Next steps

<CardGroup cols={2}>
  <Card title="Widgets" href="/references/panel-extensions/widgets">
    Render a component in a slot on an existing page.
  </Card>
  <Card title="Create a new page" href="/references/panel-extensions/create-page">
    Add a route with file-based routing and register it in the sidebar.
  </Card>
</CardGroup>