> ## Documentation Index
> Fetch the complete documentation index at: https://developers.zite.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Forms

> Build a form people fill out in a Start app: a multi-step flow, validation, partial submissions, notifications, spam handling and a review dashboard for the team.

A form is judged on two screens: the respondent's (fast, clear, works on a phone) and the owner's (submissions they can act on). Usually you build both: the form, often a public page in an external app, and a review dashboard for the team in an internal app. This page sets the defaults for each, from the respondent's first screen to the record the team reviews.

## Decide these first

Two choices change what you build. Settle them up front and take everything else from the defaults below.

1. **Partial submissions** (multi-step forms). Saving answers as people go lets the owner see where they drop off and follow up. Use it for applications, leads and orders. Leave it off for anonymous surveys, where storing unsent answers breaks the anonymity respondents expect.
2. **What happens with submissions.** A review dashboard (recommended), an email on each submission, a Slack message, a confirmation email to the respondent.

## Respondent experience

* Multi-step forms open with the title, one line on their purpose and an honest time estimate. They show progress ("Step 2 of 4" and a bar, counting only the steps branching will show) and keep answers on Back. Next validates the current step only.
* Order questions easy before hard. With partials on, ask for name and email early so a drop-off can be followed up. Sensitive and optional questions go last.
* Branching: derive the visible steps and fields from the current answers, and leave answers to hidden questions out of the payload so stale data isn't saved.
* In one-question-per-screen layouts, picking a single choice or pressing Enter advances. Multi-select and long text wait for Next.
* Keep a multi-step form's draft in `localStorage` under a key unique to the form, offer "Continue where you left off", and clear it on submit. Losing answers on a reload is the most common way long forms get abandoned. Pages render on the server first, where there is no `localStorage`, so read the draft in a `useEffect` (see [Framework overview](https://developers.zite.com/framework/overview.md)).
* The ending screen, and any confirmation email, say what happened and what comes next ("We reply within 2 business days"). A bare "Thanks!" leaves people unsure it worked.
* Lay the form out as a centred column about 600px wide, with one primary action per screen and Back as a quiet secondary. A `fillout-embed-type` URL param means the form is embedded on someone's site: drop the page background and header so it sits in the host page.

## Fields

* Labels sit above the input and stay visible. Placeholders carry format examples only, since they vanish once someone types.
* Pick the control by the shape of the answer:
  * a few options: radio buttons or clickable choice cards
  * longer lists: a `Select`, searchable once it's long
  * yes or no: two buttons
  * ratings: a segmented 1–5, or 0–10 with labelled ends for NPS
* Set `type` or `inputMode`, and `autoComplete` (`name`, `email`, `tel`, `organization`, `street-address`, `postal-code`), so phones show the right keyboard and autofill works.
* Phone: a country select plus the number, stored as E.164. Address: separate fields, or Places autocomplete when Google Maps is connected (see [Maps](https://developers.zite.com/recipes/maps.md)).
* Files: a drop zone that also opens the picker on click, with the allowed types and max size stated up front, and each picked file's name, upload state and a Remove button. See [File uploads](https://developers.zite.com/framework/file-uploads.md).
* Signature: a canvas pad with a Clear button, uploaded as a PNG through `useUpload` from `zitejs/upload`. Store the image URL, the typed name and a timestamp.

```tsx theme={"system"}
// apps/<app>/src/components/SignaturePad.tsx
import { useUpload } from 'zitejs/upload';

export function SignaturePad({ onSigned }: { onSigned: (url: string) => void }) {
  const { upload, isUploading } = useUpload();

  const save = async (canvas: HTMLCanvasElement) => {
    const blob = await new Promise<Blob | null>(resolve => canvas.toBlob(resolve, 'image/png'));
    if (!blob) return;
    const { url } = await upload(blob, 'signature.png');
    onSigned(url);
  };

  // ...the canvas, a Clear button, and a Save button that calls save()
}
```

## Validation

* Write one zod schema per step, and compose them into the submitting server function's `.validator()`. The function is public, so it validates everything the client sent again.
* Validate a field when it loses focus, then live once it shows an error, so nobody is flagged mid-word. Errors sit under the field and say how to fix it ("Enter an email like [name@company.com](mailto:name@company.com)"). A failed Next or Submit focuses the first invalid field.
* Tie each error to its field with `aria-describedby` and announce it. Group choices with `fieldset` and `legend`. A step change moves focus to the new step's heading, so keyboard and screen-reader users know where they are.
* Submit stays enabled, so a click can explain what's missing, and shows a spinner while the request is in flight. On a network failure, keep every answer and offer Retry.

## Submissions

* Use one table per form, with one field per question of the matching type, plus a `status` single select with stages that fit the domain (for example New, Reviewing, Accepted, Rejected). Public forms also store `source` and the UTM params read from the URL on first load.
* Prefill fields from URL params where it makes sense (`?email=`, `?ref=`). Owners use these in campaigns and emails. Read them with the route's `validateSearch` and `Route.useSearch()`.
* The client creates a `submissionId` when the form starts and keeps it with the draft. The server function upserts on it, so partial saves, retries and the final submit all land on one record. With partials on, each Next saves with `status: Partial` and a `lastStep` field, which the dashboard's drop-off funnel counts.
* The server function writes the record first, then runs side effects (emails, Slack, integrations) only the first time a record reaches a submitted status. Wrap each side effect in try/catch with logging, so a failing integration never loses a submission and a retry never sends twice.
* Emails to the owner or their team (a copy of each submission, a digest) go out through Zite's built-in email, which needs no connection. If the workspace has no `email` integration yet, add `"email": { "type": "email", "provider": "zite_email" }` under `integrations` in the root `zite.config.json`, and `"email": {}` to the app's `integrationSettings`. You don't need `setup_integration` for it. See [Email](https://developers.zite.com/framework/email.md).
* Some accounts must complete account verification before the built-in email sends. A send refused for that reason fails with an error that links to the verification.
* When the form also emails respondents, connect your own email account as the `email` integration's provider instead: respondents see who an email is from, and one account then sends both.
* Spam: public server functions already have platform rate limiting. Add a honeypot field (visually hidden, `aria-hidden`, `tabIndex={-1}`) and accept its submissions but silently discard them. Leave out time-to-submit checks, since prefilled and autofilled forms are legitimately fast.
* Deadlines and response caps, when you need them, are enforced in the server function and exposed as a status the form reads on load, so it opens on a closed screen instead of failing at submit.
* Submissions made in the editor preview are saved like real ones. Delete them from the database when you're done testing.

## Example: saving progress and submitting

Two `publicFn` server functions share one record per `submissionId`: `saveProgress` on each Next, `submitApplication` at the end. Both validate with the per-step schemas, and both leave a record alone once it has been submitted.

```typescript theme={"system"}
// apps/<app>/src/lib/application.functions.ts
import { z } from 'zod';
import { publicFn } from 'zitejs/start';
import { zite } from 'zitejs/db';
import { notifyTeam } from './application.server';

// One schema per step. The page validates the current step with its own.
const contactStep = z.object({
  name: z.string().min(1, { error: 'Enter your name' }),
  email: z.email({ error: 'Enter an email like name@company.com' }),
});
const detailsStep = z.object({
  role: z.enum(['Engineering', 'Design', 'Other']),
  about: z.string().max(2000).optional(),
});

export const saveProgress = publicFn({
  method: 'POST',
  description: 'Saves the answers of an application in progress',
})
  .validator(
    z.object({
      submissionId: z.uuid(),
      lastStep: z.number().int(),
      ...contactStep.partial().shape,
      ...detailsStep.partial().shape,
    }),
  )
  .handler(async ({ data }) => {
    const existing = await zite.applications.findOne({
      filters: { submissionId: data.submissionId },
    });
    if (existing && existing.status !== 'Partial') return;
    await zite.applications.bulkCreate({
      records: [{ ...data, status: 'Partial' }],
      matchOn: ['submissionId'],
    });
  });

export const submitApplication = publicFn({
  method: 'POST',
  description: 'Saves a submitted application and notifies the team',
})
  .validator(
    z.object({
      submissionId: z.uuid(),
      website: z.string().optional(), // the honeypot
      ...contactStep.shape,
      ...detailsStep.shape,
    }),
  )
  .handler(async ({ data }) => {
    const { submissionId, website, ...answers } = data;
    if (website) return { ok: true };

    const existing = await zite.applications.findOne({ filters: { submissionId } });
    // A retry of a submission that already landed: no second write, no second email.
    if (existing && existing.status !== 'Partial') return { ok: true };

    await zite.applications.bulkCreate({
      records: [{ submissionId, ...answers, status: 'New' }],
      matchOn: ['submissionId'],
    });

    try {
      await notifyTeam(submissionId); // a *.server.ts helper that sends with Email.send
    } catch (error) {
      console.error('Application saved, but the team email failed', error);
    }
    return { ok: true };
  });
```

On the page, create the `submissionId` in the browser and keep it with the draft:

```tsx theme={"system"}
// apps/<app>/src/routes/apply.tsx (inside the form component)
const DRAFT_KEY = 'apply-form-draft';
const [draft, setDraft] = useState<Draft | null>(null);
const [website, setWebsite] = useState(''); // the honeypot's value

useEffect(() => {
  const saved = localStorage.getItem(DRAFT_KEY);
  setDraft(saved ? JSON.parse(saved) : { submissionId: crypto.randomUUID(), step: 0, answers: {} });
}, []);

const save = useMutation({
  mutationFn: (draft: Draft) =>
    saveProgress({ data: { submissionId: draft.submissionId, lastStep: draft.step, ...draft.answers } }),
});

// The form keeps its answers until the submit succeeds.
const submit = useMutation({
  mutationFn: (draft: Draft) =>
    submitApplication({ data: { submissionId: draft.submissionId, website, ...draft.answers } }),
  onSuccess: () => localStorage.removeItem(DRAFT_KEY),
  onError: error => toast.error(error.message),
});

// On "Next", validate the current step, then save.mutate(draft). On "Submit", submit.mutate(draft).

```

The honeypot is an ordinary input that people never see or reach:

```tsx theme={"system"}
<input
  name="website"
  value={website}
  onChange={e => setWebsite(e.target.value)}
  aria-hidden
  tabIndex={-1}
  autoComplete="off"
  className="absolute -left-[9999px]"
/>
```

## Defaults by form type

| Type | Defaults |
| - | - |
| Contact or lead | 5 fields at most. Offer a CRM integration once it's built |
| Survey, feedback or NPS | No email field unless asked for. The dashboard leads with per-question charts |
| Application or intake | Uploads, a review step with an Edit link per section, a confirmation email. The dashboard is a status pipeline |
| Registration or order | Payment as in [Stripe payments](https://developers.zite.com/recipes/stripe-payments.md), capacity checked in the server function, a receipt email |
| Quiz or assessment | The score is computed in the server function, so the answers never ship to the browser. A result screen |
| Internal request (internal app) | Prefill the requester from the signed-in user, let requesters see the status of their own requests, no spam handling |

## Review dashboard

Build the dashboard as its own app (`create_app`) with `accessMode` set to `internal`. The form is public, submissions should be visible only to the team, and access is set per app (see [Access and sign-in](https://developers.zite.com/framework/access-and-sign-in.md)). Alongside a table of submissions, it has:

* A detail view with the answers grouped as on the form, under the question labels (not field names), with previewable files and the signature image.
* Status changes and internal notes.
* An overview: submissions over time, breakdowns of the main choice questions and, with partials on, a funnel from started through each step to submitted. Compute these with SQL, as in [Dashboards with SQL](https://developers.zite.com/recipes/dashboards-sql.md).
* CSV export of the current filtered view.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.