Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

16.0 KB
Raw Blame

paths: - "apps/erp/app/modules//ui/" - "apps/erp/app/modules//*.models.ts" - "apps/erp/app/components/Form/" - "apps/mes/app/components/" - "packages/form/"

Forms Conventions

Forms in Carbon follow a three-part pattern: zod validator (module .models.ts) → form component (ValidatedForm in ui/) → route action (validate + service call + redirect).

Real reference examples (current code):

  • apps/erp/app/modules/accounting/ui/PaymentTerms/PaymentTermForm.tsx + route actions apps/erp/app/routes/x+/accounting+/payment-terms.new.tsx (create) and payment-terms.$paymentTermId.tsx (edit).
  • apps/erp/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx + apps/erp/app/routes/x+/resources+/work-centers.new.tsx.
  • apps/erp/app/modules/inventory/ui/StorageRules/StorageRuleForm.tsx (uses .superRefine, zfd.checkbox, zfd.repeatableOfType; its validator lives in the module's one inventory.models.ts).

File Locations

Piece ERP Location MES Location
Validator app/modules/{module}/{module}.models.ts app/services/models.ts
Form UI app/modules/{module}/ui/{Feature}/{Feature}Form.tsx Inline in route or app/components/
Create action app/routes/x+/{module}+/{resource}.new.tsx app/routes/x+/{resource}.tsx
Edit action app/routes/x+/{module}+/{resource}.${id}.tsx same route
Form fields ~/components/Form (re-exports @carbon/form + domain selectors) @carbon/form directly

Import fields from the barrel ~/components/Form, not deep @carbon/form paths. The barrel re-exports every base field from @carbon/form plus the ERP domain selectors (apps/erp/app/components/Form/index.ts).

1. Validator (zod schema)

Define in the module's .models.ts. Import is import { z } from "zod" and import { zfd } from "zod-form-data" - there is NO @carbon/form schema helper; the schema is plain zod. Use zfd to coerce raw FormData strings into the right types.

import { z } from "zod";
import { zfd } from "zod-form-data";

export const thingValidator = z.object({
  id: zfd.text(z.string().optional()),               // optional id (create vs edit)
  name: z.string().min(1, { message: "Name is required" }),
  type: z.enum(thingTypes, {                          // enum with custom message
    errorMap: () => ({ message: "Type is required" })
  }),
  quantity: zfd.numeric(z.number().min(0)),           // number from FormData
  isActive: zfd.checkbox(),                           // checkbox boolean
  notes: zfd.text(z.string().optional()),             // optional text
  tags: zfd.repeatableOfType(z.string()).optional(),  // repeated form field → array
});

Validator rules

Field type Use
Optional string zfd.text(z.string().optional())
Number from FormData zfd.numeric(z.number())
Checkbox boolean zfd.checkbox()
Repeated field → array zfd.repeatableOfType(z.string())
Enum z.enum(values, { errorMap: () => ({ message }) })
Required array z.array(z.string().min(1)).min(1, { message })
Cross-field .refine() / .superRefine() on the object

2. Form Component

The core is ValidatedForm wrapping the fields. The validator prop takes the raw zod schema directly (e.g. validator={thingValidator}), NOT a wrapped validator - wrapping with validator(schema) happens only in the route action.

Real forms typically: wrap in a ModalDrawer* container (@carbon/react), pass a useFetcher() to the form, set className="flex flex-col h-full", and use Lingui t`...` for labels. Containers vary (Drawer, Modal, Card, inline) - match neighboring routes.

import { ValidatedForm } from "@carbon/form";
import {
  Button,
  HStack,
  ModalDrawer,
  ModalDrawerBody,
  ModalDrawerContent,
  ModalDrawerFooter,
  ModalDrawerHeader,
  ModalDrawerProvider,
  ModalDrawerTitle,
  VStack
} from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
import { useFetcher } from "react-router";
import type { z } from "zod";
import {
  CustomFormFields,
  Hidden,
  Input,
  Select,
  Submit
} from "~/components/Form";
import { usePermissions } from "~/hooks";
import { thingValidator } from "~/modules/things/things.models";
import { path } from "~/utils/path";

type ThingFormProps = {
  initialValues: z.infer<typeof thingValidator>;
  type?: "modal" | "drawer";
  open?: boolean;
  onClose: () => void;
};

const ThingForm = ({ initialValues, type = "drawer", open, onClose }: ThingFormProps) => {
  const { t } = useLingui();
  const permissions = usePermissions();
  const fetcher = useFetcher<{}>();

  const isEditing = initialValues.id !== undefined;
  const isDisabled = isEditing
    ? !permissions.can("update", "things")
    : !permissions.can("create", "things");

  return (
    <ModalDrawerProvider type={type}>
      <ModalDrawer open={open} onOpenChange={(o) => { if (!o) onClose?.(); }}>
        <ModalDrawerContent>
          <ValidatedForm
            validator={thingValidator}
            method="post"
            action={isEditing ? path.to.thing(initialValues.id!) : path.to.newThing}
            defaultValues={initialValues}
            fetcher={fetcher}
            className="flex flex-col h-full"
          >
            <ModalDrawerHeader>
              <ModalDrawerTitle>{isEditing ? t`Edit Thing` : t`New Thing`}</ModalDrawerTitle>
            </ModalDrawerHeader>
            <ModalDrawerBody>
              <Hidden name="id" />
              <Hidden name="type" value={type} />
              <VStack spacing={4}>
                <Input name="name" label={t`Name`} />
                <Select name="type" label={t`Type`} options={typeOptions} />
                <CustomFormFields table="thing" />
              </VStack>
            </ModalDrawerBody>
            <ModalDrawerFooter>
              <HStack>
                <Submit isDisabled={isDisabled}>{t`Save`}</Submit>
                <Button size="md" variant="solid" onClick={() => onClose?.()}>
                  {t`Cancel`}
                </Button>
              </HStack>
            </ModalDrawerFooter>
          </ValidatedForm>
        </ModalDrawerContent>
      </ModalDrawer>
    </ModalDrawerProvider>
  );
};

Form component rules

  • Type props with z.infer<typeof validator>.
  • validator={rawZodSchema} - pass the schema directly.
  • Include <Hidden name="id" /> for edit support; <Hidden name="type" value={type} /> when the action branches on modal vs page submission.
  • <CustomFormFields table="{tableName}" /> renders per-table custom fields.
  • VStack spacing={4} for vertical layout; grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-4 for multi-column.
  • Permission check drives isDisabled on <Submit>.
  • A submit button must disable while its own submission is in flight. Inside a ValidatedForm use <Submit>, which disables on isSubmitting; the form itself also drops a re-entrant submit, so the two together make a double POST impossible. On a fetcher.Form / <Form> bind the button yourself — isLoading={fetcher.state !== "idle"} (on @carbon/react's Button, isLoading disables as well as spins), or navigation.formAction === <action> for a navigation form. Every extra click is a whole extra POST: fetcher.submit aborts the previous browser request, but the server action it started runs to completion — nothing reads request.signal. A slow action (render a PDF, post a ledger entry, email a customer) is exactly where this bites, and the missing spinner is what invites the second click. Enforced by no-unguarded-submit (@carbon/checks); note that an isDisabled bound to something that is not a submit-state signal does NOT count.
  • Pass fetcher from useFetcher() when the form is a drawer/modal (so loading state and action data flow through the fetcher); plain page forms may omit it.

3. Route Action

A route action checks the request, then makes ONE service-function call, then returns its result. The write and every check it needs live in the service function (<module>.server.ts), so the API, MCP and workflows run the same logic. See module-files.md.

import { carbon, respond } from "@carbon/api/carbon.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { thingValidator } from "~/modules/things/things.models";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";

export async function action(args: ActionFunctionArgs) {
  const input = await validator(thingValidator).request(args, {
    params: ["thingId"] // only for an edit route
  });
  if ("invalid" in input) return input.invalid;

  const api = await carbon(args.request);
  const result = await api.things.updateThing({
    ...input.data,
    id: input.params.thingId,
    customFields: input.formData ? setCustomFields(input.formData) : undefined
  });

  // A fetcher form: return the result; `useAction` toasts an error.
  return result;
  // A navigating form instead: flash the error, or `message`, and redirect.
  // return respond(args.request, result).redirect(path.to.things, {
  //   message: "Thing saved"
  // });
}

Route action rules

Step Pattern
Check the request validator(schema).request(args, { method?, params? }) (@carbon/form): the method (default POST, else 405), the named route params (400), then the body (form data or JSON). Pass no schema when the action reads no body
Invalid body if ("invalid" in input) return input.invalid (the 422 validationError)
Auth carbon(args.request) (@carbon/api/carbon.server) authenticates the caller. The service function's permission is the gate, so the route has no requirePermissions
One call api.<module>.<name>(input). No write in the route itself (a .from(...) write, Kysely, invokePosting): the route-action-shape check fails it
Custom fields setCustomFields(input.formData) (~/utils/form) when the body is form data
Fetcher form return result
Navigating form return respond(args.request, result).redirect(to, { message, onError })

Actions return plain objects or data(value, init). Do NOT use json(...) - that is the old Remix helper and is not used here.

Legacy shape

Many actions still call a building block directly. They keep the old order until their module migrates: assertIsPost(request) → requirePermissions(request, { create | update: "module" }) → const formData = await request.formData() → validator(schema).validate(formData) → return validationError(validation.error) on failure → the service call → return data({}, await flash(request, error(...))) on failure, or throw redirect(path, await flash(request, success(...))) on success (a modal branch may return data(row, { status: 201 })). Do not write new actions this way.

4. Route Default Export

Page (non-modal) routes export a default component that renders the form:

export default function NewThingRoute() {
  const initialValues = { name: "", type: "Default" as const };
  return <ThingForm initialValues={initialValues} />;
}

Edit routes load data in the loader and pass it through:

export default function EditThingRoute() {
  const { thing } = useLoaderData<typeof loader>();
  return <ThingForm initialValues={thing} />;
}

Drawer/modal forms are often rendered by a parent list route instead of having their own default export; the route file may then be action-only.

Available Form Components

Base fields (@carbon/form, re-exported by ~/components/Form)

Source: packages/form/src/components/.

Component Notable props Use for
Input / InputControlled name, label, prefix?, suffix? Text
Number / NumberControlled name, label, formatOptions?, minValue?, maxValue? Numeric with steppers
TextArea / TextAreaControlled name, label Multi-line
Select / SelectControlled name, label, options: {label,value}[] Dropdown
Combobox name, label, options Searchable dropdown
CreatableCombobox name, label, options, onCreateOption? Searchable + create
MultiSelect / CreatableMultiSelect name, label, options Multi-select
Boolean name, label, description? Switch/toggle
Radios name, label, options Radio buttons
DatePicker / DateTimePicker / TimePicker name, label Date / time
Timezone name, label Timezone select
Hidden name, value? Hidden field
Password name, label Password with toggle
PhoneInput name, label Phone
InputOTP name OTP code
Array / ArrayNumeric name, label Dynamic list fields
Submit / DefaultDisabledSubmit isDisabled?, withBlocker? Submit button
ChoiceCardGroup options Card-style choice group

Domain selectors (~/components/Form only)

Combobox/CreatableCombobox wrappers that auto-load options from stores - use these instead of a raw Combobox when the entity matches. Current set (apps/erp/app/components/Form/index.ts):

Abilities, Ability, Account (+AccountControlled), AddressAutocomplete, AssetClass, Color, ConversionFactor, CostCenter, Currency, Customer, CustomerContact, CustomerLocation, CustomerStatus, Customers, CustomerType, CustomerTypes, CustomFormFields, DefaultMethodType, Department, EmailRecipients, EmojiPicker, Employee, Employees, Item, ItemPostingGroup, Items, Location, MaterialType, Part, PaymentTerm, Procedure, Process, Processes, Sequence, SequenceOrCustomId, Service, ShelfLifeStartProcess, ShelfLifeStartTiming, Shift, ShippingMethod, StandardFactor, StorageTypes, StorageUnit, Supplier, SupplierContact, SupplierLocation, SupplierProcess, SupplierStatus, Suppliers, SupplierType, Tags, Tool, UnitHint, UnitOfMeasure, User, Users, WorkCenter, WorkCenters.

Common Patterns

Dependent fields

const [categoryId, setCategoryId] = useState(initialValues.categoryId ?? "");

<AccountCategory name="categoryId" onChange={(cat) => setCategoryId(cat?.id ?? "")} />
<AccountSubcategory name="subcategoryId" accountCategoryId={categoryId} />

Enum options from const array

const typeOptions = thingTypes.map((t) => ({ label: t, value: t }));
<Select name="type" label="Type" options={typeOptions} />

Cache invalidation

Nothing to write. The root client middleware (createInvalidationMiddleware, @carbon/query) marks every cached loader entry stale after any action, so a form's route does not export a clientAction and does not name the lists it changes. See clientAction-patterns.md.

Reacting to the result

Use useAction from @carbon/query instead of useFetcher plus an effect that watches fetcher.data:

const fetcher = useAction<typeof action>({
  onSuccess: () => onClose(),
  onError: (data) => toast.error(data.message)
});
// <ValidatedForm fetcher={fetcher} …> or fetcher.submit(…), as before

Checklist

  • Zod validator in {module}.models.ts (import { z } from "zod" + zfd)
  • Validator imported from ~/modules/{module}/{module}.models (modules have no barrel)
  • Form component with ValidatedForm, raw schema in validator prop
  • Props typed with z.infer<typeof validator>; <Hidden name="id" /> present
  • Route action: validator(schema).request(args, …) → carbon(request) → one service-function call → return the result or respond(...).redirect(...)
  • setCustomFields(formData) + <CustomFormFields table="..." /> if the table has custom fields
  • Path helpers in ~/utils/path (use path.to.*, never hardcoded URLs)
  • Container matches neighboring routes (ModalDrawer, Card, inline, etc.)