- Resolve conflicts in analytics, consent, content, i18n, mcp and stats, keeping the docs fixes and the new code behaviour, verified against src - Translate the remaining 14 module pages, ipal-seo-check skill and script - Integrate the security-perf and SEO agent-guide text: getRobots, isPathVisible, Search & AI (DNS verification first, meta fields optional), sitemap index/cache/503, consentMode basic/advanced, policyVersion, globalOverrides, revalidatePath / buildGlobalRevalidateHook, authAccess, firstUserAdmin, allowCollectionMismatch, unknown-IP rate limit; stale claims fixed across AGENT.md, skills, frontend, developer guide, vibe - docsConsistency: pending list removed (all docs English); relative links now also check #anchors Co-Authored-By: Claude Opus 5.5 <[email protected]>
654 lines
34 KiB
Markdown
654 lines
34 KiB
Markdown
# forms
|
||
|
||
Wires `@payloadcms/plugin-form-builder` (forms + form-submissions collections) and
|
||
provides `submitForm` — a server function (called from a Server Action) that chains:
|
||
rate limit → Turnstile → validation against the form definition from the panel → storing the submission.
|
||
Emails are sent by the form-builder (Forms → Emails) through `mailAdapter()`.
|
||
|
||
## ⚠️ RULE: the form COMES FROM the builder in the panel (mandatory)
|
||
|
||
**Forms are built by the editor in the panel** (Forms collection), NOT by the developer in code.
|
||
This is a CMS — the client defines fields, labels, messages and the recipient. The front end
|
||
only RENDERS the form from the panel and submits it through `submitForm`.
|
||
|
||
**NEVER build your own hard-coded form** — with hand-written
|
||
fields, labels in JSX, your own validation. It breaks "nothing hard-coded" (the client cannot
|
||
change fields or texts) and skips the plugin's whole mechanism (Turnstile, rate limit,
|
||
GDPR consent, notifications).
|
||
|
||
| WRONG (your own form) | RIGHT (the plugin's builder) |
|
||
|---|---|
|
||
| `<input name="email" placeholder="Email" />` in JSX | fields from the Forms collection (panel) |
|
||
| labels/messages in code | labels per language in the panel |
|
||
| your own validation/submit | `submitForm` (Turnstile+consent+mail) |
|
||
| the client cannot change the form | the client edits fields in the panel |
|
||
|
||
**How to do it right:** the editor creates a form in the Forms collection → a block renders it
|
||
with `<RenderForm>` → it is submitted through `sendForm` (`createSubmitAction` → `submitForm`). Fields,
|
||
labels, messages, recipient — all from the panel.
|
||
|
||
If a form needs a field the builder does not have — add it through the `fields`
|
||
configuration (see below) or extend the plugin. Do NOT hard-code your own form.
|
||
|
||
## Dependency
|
||
|
||
```json
|
||
"dependencies": { "@payloadcms/plugin-form-builder": "3.90.2" } // same version as payload
|
||
```
|
||
(the plugin's peer dependency: `^3.90.2`)
|
||
|
||
## Config (payload.config.ts)
|
||
|
||
```ts
|
||
ipalKit({
|
||
forms: {
|
||
redirectRelationships: ['pages'], // a form can redirect to a Page
|
||
// fields: { date: false, … }, // default: text, textarea, email, number, date,
|
||
// // time, select, radio, checkbox, checkboxGroup, message, step
|
||
},
|
||
})
|
||
```
|
||
|
||
`forms` options (`FormsOption`):
|
||
|
||
| Option | Default | Description |
|
||
|---|---|---|
|
||
| `adminGroup` | `'Forms'` | group in the panel; `false` = Payload's default; `admin.group` in overrides wins |
|
||
| `fields` | see below | builder field types; `false` turns a type off, an object (block) replaces it; `true` = the default ipal block |
|
||
| `redirectRelationships` | — | collections a form can redirect to |
|
||
| `formOverrides` / `formSubmissionOverrides` | — | collection overrides (`fields` as a function + any collection settings) |
|
||
| `emailLayout` | `false` | nice emails + the Site Settings → Emails tab |
|
||
| `beforeEmail` | — | the form-builder's `beforeEmail` (after the layout, when `emailLayout`) |
|
||
| `consentFieldName` | `'consent'` | name of the GDPR consent field for `submitForm` / `createSubmitAction` (the call's argument wins) |
|
||
|
||
`payment` is always off — `fields: { payment: true }` does **not** turn it on (the value `true`
|
||
is skipped); it can only be turned on by passing a block object. `country` / `state` keep the form-builder's
|
||
default settings.
|
||
|
||
Adds the **Forms** (the editor builds forms) and **Form Submissions**
|
||
(submissions) collections — in the panel in the **Forms** group with the labels "Form/Forms" and
|
||
"Submission/Submissions" (no overrides needed in the project). A different group:
|
||
`forms: { adminGroup: 'Content' }`; Payload's default: `adminGroup: false`. Emails after a submission are sent by the form-builder according to the form's **Emails**
|
||
tab — through the adapter from `email:` in the config (the "Emails" section below).
|
||
|
||
## Front end — RenderForm (recommended, one line)
|
||
|
||
The whole front end of a panel form lives in the plugin. The project has the block and the classes:
|
||
|
||
```tsx
|
||
// src/blocks/FormBlock/Component.tsx
|
||
import { RenderForm } from '@intecion/ipal-kit/rsc'
|
||
<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
|
||
```
|
||
- `form` — the relation from the block (depth ≥ 1; an ID or null → nothing renders),
|
||
- `action` — `sendForm` from `createSubmitAction` (below), `texts` — `getFormTexts(locale)` from `lib/content`
|
||
(Notifications → Form messages),
|
||
- `classNames` — the **only** place for looks (`src/components/forms/formClasses.ts`, template in ipal-form);
|
||
the plugin has no styles at all. Keys: `form, progress, step, stepTitle, stepDescription, fields,
|
||
field, fieldHalf, fieldFull, label, input, textarea, select, checkbox, checkboxLabel, choices,
|
||
legend, choice, choiceInput, choiceLabel, message, error, formError, turnstile, actions, back,
|
||
next, submit, success, required, fixed`. For CSS there are also `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
|
||
- options: `requiredMark` (e.g. `" *"`), `converters` / `richTextClassName` (rich text looks),
|
||
`linkOptions` (`await getLinkOptions(locale)` — redirect to a page from the panel), `turnstileTheme`
|
||
(default `'page'`), `values` (below).
|
||
|
||
`RenderForm` (server) renders **message** blocks and the confirmation through `RenderRichText`, binds
|
||
the action to the form and the language, resolves the redirect and gives the browser **only the public part of the
|
||
form** — the Local API reads with `overrideAccess`, so the document has the Emails tab (company addresses);
|
||
a hand-written `<FormRenderer form={form}>` used to send them in the HTML. Underneath it is `BuilderForm` (client).
|
||
|
||
### Field types in the panel
|
||
text, email, textarea, number, **date**, **time** (1.11.1), select, **radio**, checkbox, **Checkbox group**,
|
||
message, **Step** (+ country/state as text). Turning a type off: `forms.fields: { date: false }`.
|
||
|
||
**Placeholder** (1.11.1): text, email, textarea and number have a localized "Placeholder" field — a hint
|
||
in the empty field ("e.g. 10:00–12:00"). `BuilderForm` and `useBuilderForm` (`getInputProps`, `getTextareaProps`)
|
||
pass it on by themselves. Your own block with this field: `withPlaceholder(block)` / `placeholderField` from the root;
|
||
the time block: `timeBlock`. New fields in form blocks = a migration (`pnpm payload migrate:create`).
|
||
|
||
| Type | Value | The server checks |
|
||
|---|---|---|
|
||
| radio, select | one value | only values from the panel |
|
||
| Checkbox group | `string[]` (stored as "www, seo") | only values from the panel, no duplicates, `minSelected`/`maxSelected` |
|
||
| date | `YYYY-MM-DD` | a real date |
|
||
| time | `HH:MM` (`<input type="time">`) | a time 00:00–23:59 |
|
||
| Step | — (split) | not a field |
|
||
|
||
### Multi-step form
|
||
A **Step** block (title, description, per language) starts a new screen; fields above the first Step are screen 1.
|
||
`BuilderForm`: "Step 1 of 3" (`stepOf`), Next validates only the current step, Back keeps the
|
||
values, focus moves to the new step, Turnstile is on the last step, a field error from the server goes back
|
||
to the step with that field. Button texts: Notifications → Form messages → `next`, `back`, `stepOf`.
|
||
|
||
### Conditional fields and steps ("Show only when")
|
||
Every form block (built-in, **Checkbox group**, **Step**, message) has a
|
||
**Show only when** group in the panel (`showWhen`): `field` — the technical name of another field, `values` — option values,
|
||
comma-separated (empty = when that field is filled in / checked). An empty `field` = always visible.
|
||
|
||
- On a field: the field shows up only for a matching answer (e.g. "What sets the deadline?"
|
||
only when `deadline = fixed`).
|
||
- On a **Step**: the whole step (with its fields) drops out when the condition does not match — the following steps are renumbered
|
||
("Step 2 of 3"). This is how a brief is built: screen 1 picks areas (Checkbox group), each following
|
||
Step has `showWhen: { field: 'areas', values: 'web' }`.
|
||
- A field in a hidden step is hidden, even when its own condition matches; a condition that points at a hidden field
|
||
does not match either. The name of a field that does not exist (a typo) or a cycle hides the field — you can see it in the preview.
|
||
- One shared rule `visibleFields(fields, values)` (`@intecion/ipal-kit`, `/client`) — the browser
|
||
(`useBuilderForm`/`BuilderForm`: what to show, validate and send) and the server (`validateSubmission`):
|
||
a hidden field **is not required and is not stored**, even when someone sends it by hand.
|
||
Exception: the GDPR consent field (`consent`) is always enforced — a condition cannot turn it off.
|
||
- The `FieldCondition` type (`{ field, values }`) for your own markup on `useBuilderForm`; `splitSteps(fields, isShown)`
|
||
skips hidden fields and steps, keeping the original `index` (message blocks render by it).
|
||
- The new group = columns `show_when_field` / `show_when_values` in the form block tables →
|
||
after updating, generate a migration (`payload migrate:create`).
|
||
|
||
### Field values from the page (`values`, 1.11.0)
|
||
The page knows a field value the visitor does not type — the chosen product variant, category, offer.
|
||
The editor adds a plain text field to the form (e.g. `subject`, "Regarding"), and the page fills it:
|
||
|
||
```tsx
|
||
// a value known on the server (the "coming soon" category)
|
||
<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} values={{ subject: category.title }} />
|
||
```
|
||
A field with `values` is shown read-only (`<output>`, class `classNames.fixed`, `data-ipal="form-fixed"`),
|
||
sent like any other field and validated by the server against the definition from the panel. Names not in the form are skipped.
|
||
The value is in the first HTML (SSR), not only after hydration.
|
||
|
||
A value that changes in the browser (a configurator): the server prepares the form with `prepareBuilderForm` (`/rsc`) —
|
||
the public part (`publicForm`, without the Emails tab), the rendered message blocks and confirmation, the action bound
|
||
to the form and the language, the redirect target — and a client component renders `BuilderForm` with the current `values`:
|
||
|
||
```tsx
|
||
// server
|
||
const form = prepareBuilderForm({ form: catalog.inquiryForm, action: sendForm, locale })
|
||
<Configurator form={form} texts={formTexts} />
|
||
// client ('use client')
|
||
<BuilderForm {...form} texts={texts} classNames={formClasses} values={{ subject: chosenVariant }} />
|
||
```
|
||
`publicForm(form)` (`/rsc`) — just the public part of the document, when you build your own hand-off to the client. Never
|
||
pass the raw form document to the browser.
|
||
|
||
### An unusual form — without copying the engine
|
||
1. `renderField` (BuilderForm in a `'use client'` file) — replaces selected fields:
|
||
`renderField={({ field, defaultRender }) => field.name === 'budget' ? <Cards …/> : undefined}`.
|
||
2. `useBuilderForm({ form, action, texts })` — all the logic, the markup is yours: `steps`, `step`,
|
||
`stepIndex`, `total`, `isFirst/isLast`, `next()`, `back()`, `goTo(i)`, `submit`, `values`,
|
||
`errors`, `errorMessage`, `isSubmitting`, `isSuccess`, `resultMessage`, `isFixed`, `getFieldProps`,
|
||
`getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`,
|
||
`TurnstileWidget`. Example: `ipal-form/resources/CustomForm.example.tsx`.
|
||
3. Pure logic (also on the server / in tests): `splitSteps`, `initialBuilderValues`,
|
||
`validateBuilderFields`, `stepOfField`, `inputFields`, `visibleFields`, `autoCompleteFor` (autocomplete hint from the field's type and name).
|
||
|
||
`useOptionalTurnstile()` — like `useTurnstile`, but without a provider it returns `enabled: false` instead of throwing.
|
||
|
||
## Front end — submitForm (server)
|
||
|
||
Call it in a Server Action. The shape matches `useForm` / `useContactForm` 1:1
|
||
(`(values, turnstileToken) → { success, message }`) — you attach `formId` and `locale`
|
||
with `.bind`, and turn the error code into text from the panel:
|
||
|
||
```ts
|
||
// src/app/(frontend)/[locale]/actions.ts
|
||
'use server'
|
||
import { headers } from 'next/headers'
|
||
import { submitForm } from '@intecion/ipal-kit/server'
|
||
import { clientIp, isHoneypotTripped, HONEYPOT_FIELD, getNotificationTexts, resolveFormMessage } from '@intecion/ipal-kit'
|
||
import { getCachedPayload } from '@/lib/content'
|
||
|
||
export async function sendForm(
|
||
formId: string,
|
||
locale: string,
|
||
values: Record<string, unknown>,
|
||
turnstileToken?: string,
|
||
) {
|
||
const payload = await getCachedPayload()
|
||
const texts = (await getNotificationTexts({ payload, locale })).form
|
||
if (isHoneypotTripped(values)) return { success: true, message: texts.success } // bot: fake success
|
||
const { [HONEYPOT_FIELD]: _hp, ...data } = values
|
||
const ip = clientIp(await headers()) || undefined // headers(): OK in a server action — NOT in the page tree (SSG)
|
||
const result = await submitForm({ payload, formId, data, turnstileToken, ip })
|
||
return { success: result.success, message: resolveFormMessage(result, texts) }
|
||
}
|
||
```
|
||
|
||
```tsx
|
||
// in a client component:
|
||
const f = useForm({ initialValues, validate, submitAction: sendForm.bind(null, form.id, locale) })
|
||
```
|
||
|
||
`submitForm` result: `{ success: true, submissionId }` or `{ success: false, reason, … }`
|
||
(codes below). Options: `payload`, `formId`, `data` (required), `ip`, `locale`, `turnstileToken`,
|
||
`maxPerMinute` (default 5, `0` turns it off; without `ip` — the shared `unknown-ip` bucket, below),
|
||
`consentFieldName` (default from `ipalKit({ forms })`, then `'consent'`), `turnstileOnConfigError`
|
||
(`'allow'` | `'reject'`, default `'allow'`), `turnstileHostnames` (see [turnstile.md](./turnstile.md)).
|
||
|
||
Simpler: `createSubmitAction({ getCachedPayload, headers })` from `/server` (section 1.9.1 below) —
|
||
extra options: `clientIp`, `honeypotField`, `consentFieldName`, `maxPerMinute`,
|
||
`turnstileOnConfigError`, `turnstileHostnames`.
|
||
|
||
### Client IP and rate limit
|
||
|
||
`clientIp(req | headers, { header?, trustedProxies? })` (from `@intecion/ipal-kit`):
|
||
|
||
- **Pinned header** — `header` or the env **`IPAL_IP_HEADER`**: only that header is read (missing → empty
|
||
string). For `x-forwarded-for` it takes the `trustedProxies`-th entry (default 1) from the right.
|
||
- **Not pinned** (default): it trusts **any** of the headers, in this order: `cf-connecting-ip`,
|
||
`x-real-ip`, then `X-Forwarded-For` counted **from the right** (the client writes the left part itself). A client
|
||
that reaches the app bypassing the proxy can therefore inject `cf-connecting-ip` /
|
||
`x-real-ip` and dodge the limit. In production without `IPAL_IP_HEADER` there is a one-time warning in the log.
|
||
Set e.g. `IPAL_IP_HEADER=cf-connecting-ip` behind Cloudflare, `x-forwarded-for` only behind Traefik/nginx.
|
||
- No recognised IP → the shared bucket (below). The same `clientIp` option exists in `createSearchRoute`
|
||
and `createMcpRoute`.
|
||
|
||
A missing IP (the proxy strips the header, a wrong `IPAL_IP_HEADER`) does **not** bypass the limit: such requests
|
||
share one `unknown-ip` bucket with a ×20 limit (`UNKNOWN_IP_FACTOR`) — real
|
||
visitors get through, a flood without the header does not. `setUnknownIpFactor(n)` (root, once at startup)
|
||
changes the multiplier; `setUnknownIpFactor(0)` = the old behaviour (no limit), when a limiter sits in front.
|
||
Without a pinned header the order
|
||
`cf-connecting-ip` → `x-real-ip` → XFF stays (switching to XFF-only, from the right, would put every visitor
|
||
behind Cloudflare into the bucket of the edge node) — that is why `IPAL_IP_HEADER` is mandatory in production
|
||
(`ipalEnvRules({ ipHeader: true })`).
|
||
|
||
Limits are kept in memory by default, separately for each instance. Several instances
|
||
→ a shared store (e.g. Redis) once at startup: `setRateLimitStore({ hit })`
|
||
(example in the `RateLimitStore` JSDoc). When the store fails, the request goes through (a warning in the log).
|
||
|
||
## Flow and guarantees
|
||
|
||
1. **Rate limit** per IP → `rate_limited`.
|
||
2. **Turnstile** — the **server** configuration decides, not whether the front end sent a token.
|
||
Both keys set (panel or env) → the token is **required**: missing or failed →
|
||
`turnstile`, rejected **before** storing. Keys not set → the widget does not
|
||
show, and the check is skipped. Details: [turnstile.md](./turnstile.md).
|
||
3. **Validation** against the form definition from the panel (+ enforced GDPR consent).
|
||
4. **Storing** the submission (form-submissions) → the form-builder sends the emails from the Emails tab.
|
||
|
||
**A stored submission = success, even when the email fails** — Payload logs the sending error,
|
||
the submission data is not lost (it is in Form Submissions).
|
||
|
||
## Emails
|
||
|
||
The plugin does not compose form emails. After storing a submission, the form-builder sends the
|
||
messages the editor configured (Forms → form → Emails), through
|
||
`payload.sendEmail`. For them to go out, the config needs an adapter:
|
||
|
||
```ts
|
||
email: mailAdapter(), // from '@intecion/ipal-kit' — SMTP or Graph according to the panel (email.md)
|
||
```
|
||
|
||
Then they go through the transport chosen in Site Integrations (SMTP or Graph). The editor sets recipients, subject and
|
||
body (placeholders: `{{field}}`, `{{*}}`, `{{*:table}}`) without touching the code.
|
||
|
||
`submitForm` is responsible only for Turnstile verification and storing. It stores the submission in the page's language
|
||
(`locale` from `createSubmitAction`), so the form-builder takes the email texts and labels in that language.
|
||
|
||
### Nice emails (`emailLayout`)
|
||
|
||
```ts
|
||
forms: { emailLayout: true } // optional: beforeEmail: (emails, args) => emails (after the layout)
|
||
```
|
||
|
||
- `{{*:table}}` turns into a **readable summary**: the question text instead of the field name, option labels
|
||
instead of values (Checkbox group too), a checked checkbox = ✓, empty answers skipped, groups by
|
||
step (Step titles). Only fields the visitor saw (the server does not store fields hidden by a condition).
|
||
- Every email gets a **template** (tables + inline CSS — Gmail, Outlook, Apple Mail): a header with the logo,
|
||
the body from the panel, a footer. Settings: **Site Settings → Emails** — logo (**PNG/JPG**, SVG does not work in
|
||
Gmail/Outlook; empty = the site name), accent colour (hex), footer (per language). The link to the site and the
|
||
absolute logo address come from `serverURL` in `buildConfig` (set it from `NEXT_PUBLIC_SERVER_URL`).
|
||
- An error while building the template never blocks sending — the original email goes out, the error goes to the log.
|
||
- New tab = a migration in the project (`payload migrate:create`).
|
||
|
||
## Your own fields in the forms collection
|
||
|
||
`formOverrides` goes straight to the form-builder — the plugin has no opinion about what
|
||
a form needs beyond its own fields:
|
||
|
||
```ts
|
||
ipalKit({
|
||
forms: {
|
||
redirectRelationships: ['pages'],
|
||
formOverrides: {
|
||
fields: ({ defaultFields }) => [
|
||
...defaultFields,
|
||
{ name: 'internalNote', type: 'textarea' },
|
||
],
|
||
admin: { group: 'Content' },
|
||
},
|
||
// formSubmissionOverrides: { ... } // the same for submissions
|
||
},
|
||
})
|
||
```
|
||
|
||
`fields` gets the collection's default fields and returns the final list — you can add,
|
||
remove and reorder. Besides `fields` it accepts any collection settings
|
||
(admin, access, hooks).
|
||
|
||
## Security and the submission result
|
||
|
||
`submitForm` passes three gates in order of increasing cost: rate limit
|
||
(in-memory, per IP), Turnstile, validation against the form schema. Only
|
||
then does it store. A flood dies before it touches the network or the database.
|
||
|
||
**REST is closed.** By default the form-builder lets anyone create submissions through
|
||
`POST /api/form-submissions` — skipping all the gates below. ipal-kit
|
||
sets `access.create` of the `form-submissions` collection to "logged-in users only"; the front end
|
||
submits through `submitForm` (server action → Local API), so this does not affect it.
|
||
A deliberately public REST (e.g. an external app) →
|
||
`forms: { formSubmissionOverrides: { access: { create: () => true } } }` — then
|
||
the `submitForm` safeguards do not apply on that path.
|
||
|
||
**Only `editor+` edits forms.** The `forms` collection is publicly readable (the fields render the
|
||
form), but `create`/`update`/`delete` and reading the Emails tab (recipients, BCC) require the role
|
||
`editor` or `admin` — a `user` account cannot add itself as BCC to every submission. Override:
|
||
`forms: { formOverrides: { access: { … } } }`.
|
||
|
||
Validation matters, because a server action is a public endpoint — it can be called
|
||
without the form. The plugin loads the form definition and: rejects unknown
|
||
keys, enforces `required` fields, truncates length (5000 characters). Only what the
|
||
form defines reaches the database.
|
||
|
||
Rate limit: 5/min/IP by default (60 s window, the `form` counter is separate from search and MCP),
|
||
`maxPerMinute` changes it, `0` turns it off (when a limiter sits in front). In-memory — with several
|
||
instances the counter is per process (unless `setRateLimitStore`).
|
||
|
||
Unknown keys in `data` (other than form fields and `cf-turnstile-response` /
|
||
`g-recaptcha-response`) reject the **whole** submission (`kind: 'unknown_fields'`).
|
||
|
||
### Honeypot — a free second anti-spam layer
|
||
|
||
A hidden field that a real user neither sees nor fills in, but a naive bot
|
||
does. Zero friction (no network, no interaction), alongside Turnstile. Pure functions —
|
||
the client renders the input, the server checks it:
|
||
|
||
```tsx
|
||
// front end — in the form:
|
||
import { honeypotInputProps } from '@intecion/ipal-kit/client'
|
||
<input {...honeypotInputProps()} /> // off-screen, aria-hidden, tabIndex -1
|
||
```
|
||
|
||
```ts
|
||
// server action — CHECK FIRST, before submitForm:
|
||
import { isHoneypotTripped, HONEYPOT_FIELD } from '@intecion/ipal-kit'
|
||
if (isHoneypotTripped(values)) return { success: true } // fake success (no signal to the bot)
|
||
const { [HONEYPOT_FIELD]: _hp, ...clean } = values // remove it so submitForm does not see an unknown field
|
||
return submitForm({ /* … */ data: clean })
|
||
```
|
||
|
||
The field name defaults to `company_url` (looks real to a bot); your own:
|
||
`honeypotInputProps('website_2')` + `isHoneypotTripped(values, 'website_2')`.
|
||
|
||
### The result is a CODE, not text
|
||
|
||
`submitForm` returns a structured error — the plugin says WHAT happened, the project
|
||
decides HOW to show it (language, wording, per-field handling):
|
||
|
||
```ts
|
||
type SubmitFormResult =
|
||
| { success: true; submissionId: string | number }
|
||
| { success: false; reason: 'rate_limited' }
|
||
| { success: false; reason: 'turnstile' }
|
||
| { success: false; reason: 'validation'; field?: string; kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' }
|
||
| { success: false; reason: 'not_found' }
|
||
| { success: false; reason: 'consent'; field?: string }
|
||
| { success: false; reason: 'error' }
|
||
```
|
||
|
||
The front end maps codes to its own messages:
|
||
|
||
```tsx
|
||
function errorMessage(r) {
|
||
switch (r.reason) {
|
||
case 'rate_limited': return 'Too many submissions...'
|
||
case 'validation':
|
||
if (r.kind === 'required') return 'Fill in the required fields.'
|
||
// r.field → highlight the specific field
|
||
}
|
||
}
|
||
```
|
||
|
||
The same pattern as consent: the plugin does not hard-code a language, it hands over data.
|
||
|
||
|
||
## GDPR consent (consent field)
|
||
|
||
The GDPR consent field is the field named `consent` (the name is changed by the `consentFieldName` argument
|
||
of `submitForm` / `createSubmitAction`). The plugin ENFORCES it being checked SERVER-SIDE
|
||
(the value must be exactly `true`) — regardless of how the editor set up the field
|
||
in the panel and of the "Show only when" condition.
|
||
|
||
### Why server-side
|
||
|
||
Consent is enforced in `validateSubmission`, not by a flag in the panel. It is the only
|
||
place the editor cannot weaken (by forgetting `required`) or break
|
||
(by setting `defaultValue: true` — a pre-checked box, which GDPR forbids), and the
|
||
front end cannot bypass. If the form has a `consent` field, it MUST be checked,
|
||
otherwise `submitForm` returns `reason: 'consent'`.
|
||
|
||
### How to use
|
||
|
||
1. The editor adds a checkbox named `consent` in the panel, with a label like "I accept the
|
||
privacy policy [link]" (the policy link goes into the label — the consent text
|
||
belongs to the panel).
|
||
2. The plugin enforces it being checked. Unchecked → `reason: 'consent'`.
|
||
3. The message comes from the notifications module (`notifications.form.consent`, per language).
|
||
|
||
Renaming the field:
|
||
|
||
```ts
|
||
export const sendForm = createSubmitAction({ getCachedPayload, headers, consentFieldName: 'zgoda' })
|
||
// or: submitForm({ …, consentFieldName: 'zgoda' })
|
||
```
|
||
|
||
Or once for the whole site: `ipalKit({ forms: { consentFieldName: 'zgoda' } })` — `submitForm`
|
||
reads it from `payload.config.custom.ipal` when the call does not pass one.
|
||
|
||
## Messages — resolveFormMessage (recommended)
|
||
|
||
Instead of a hand-written switch on `reason`, use `resolveFormMessage` from the
|
||
notifications module — it maps the code to text from the panel, per language, with `{field}` interpolation:
|
||
|
||
```tsx
|
||
import { resolveFormMessage, getNotificationTexts } from '@intecion/ipal-kit'
|
||
|
||
const notifications = await getNotificationTexts({ payload, locale })
|
||
// in FormRenderer:
|
||
if (!result.success) {
|
||
setError(resolveFormMessage(result, notifications.form))
|
||
}
|
||
```
|
||
|
||
It handles ALL codes (including `consent`, `rate_limited`, `validation` with
|
||
`{field}`) with texts from the panel. Keep the hand-written switch (above) only if you do not
|
||
use the notifications module. Details: [notifications.md](./notifications.md).
|
||
|
||
## Client logic — useForm / useContactForm (lower level)
|
||
|
||
For panel forms use `RenderForm` / `useBuilderForm` (above) — they have steps, choice
|
||
lists and validation from the field definition. `useForm` is the engine underneath: for a form **outside
|
||
the builder** (e.g. a search with filters), not for contact forms.
|
||
|
||
`submitForm` is the server. On the client side the same plumbing was repeated in
|
||
every project: `useState` for fields, an email regex, the Turnstile token, submit,
|
||
success/error state — ~150 lines of identical code per project. It was moved into a
|
||
hook. **The hook renders NO markup at all** — the project keeps 100% control
|
||
over the looks (the rule "we do not take control over the looks away from projects").
|
||
|
||
This is a LOGIC layer, not a replacement for the builder. The rule "fields from the builder" still
|
||
applies: for forms the editor can edit, you build `initialValues` and
|
||
rules from the definition in the panel and pass them to `useForm` (dynamic variant below).
|
||
`useContactForm` is a preset for a classic contact form with fixed
|
||
fields — when that is deliberately the right choice.
|
||
|
||
The anti-pattern the hook removes is **duplicated logic** (validation/submit/
|
||
Turnstile by hand in every project), not "using a hook".
|
||
|
||
### Preset — contact form (zero validators)
|
||
|
||
```tsx
|
||
'use client'
|
||
import { useContactForm } from '@intecion/ipal-kit/client'
|
||
|
||
const f = useContactForm({
|
||
submitAction, // your server action that calls submitForm
|
||
requireTurnstile: Boolean(siteKey),
|
||
requireTopic: topics.length > 0,
|
||
requireConsent: Boolean(consentText),
|
||
})
|
||
// JSX and classes are yours — only the wiring comes from the hook:
|
||
<input value={f.values.email} onChange={(e) => f.setField('email', e.target.value)}
|
||
className={f.errors.email ? 'border-red-500 …' : '…'} />
|
||
<form onSubmit={f.handleSubmit}>…</form>
|
||
{f.isSuccess && <SuccessPanel onReset={f.reset} />}
|
||
```
|
||
|
||
Preset fields: `name, email, phone, topic, message, consent`. Returns:
|
||
`values, errors, isSubmitting, isSuccess, errorMessage, turnstileToken,
|
||
setField, setValues, setTurnstileToken, handleSubmit, reset`.
|
||
|
||
### Generic engine — any / dynamic fields
|
||
|
||
```tsx
|
||
import { useForm, buildValidator, required, email, minLength, pattern } from '@intecion/ipal-kit/client'
|
||
|
||
const f = useForm({
|
||
initialValues: { company: '', nip: '', email: '', message: '' },
|
||
submitAction,
|
||
validate: buildValidator({
|
||
company: [required()],
|
||
nip: [required(), pattern(/^\d{10}$/, 'NIP = 10 digits')],
|
||
email: [required(), email()],
|
||
message: [required(), minLength(10)],
|
||
}),
|
||
})
|
||
```
|
||
|
||
Dynamic fields from the builder — the schema is built at runtime from the definition in the panel:
|
||
|
||
```tsx
|
||
const initialValues = Object.fromEntries(fields.map((fl) => [fl.name, fl.type === 'checkbox' ? false : '']))
|
||
const validate = buildValidator(Object.fromEntries(fields.map((fl) => [fl.name, fl.required ? [required()] : []])))
|
||
const f = useForm({ initialValues, submitAction, validate })
|
||
```
|
||
|
||
### Validators (pure — also server-side)
|
||
|
||
`required`, `email`, `minLength`, `maxLength`, `checked`, `pattern`, `custom`,
|
||
`isEmail`, `buildValidator`. Each takes its own message. They are pure (no
|
||
`'use client'`), so you can use the same rules to re-validate in a server action.
|
||
|
||
### errors are a STRING, not a boolean
|
||
|
||
`errors.<field>` is a message (truthy when there is an error). It works as a `className` condition
|
||
like the old boolean, and you also get text to display. `setField` clears the field's error
|
||
on edit (by default).
|
||
|
||
### GTM/analytics event after submitting (Lead/Pixel)
|
||
|
||
A "Lead" tag (Meta Pixel / GA) in GTM usually fires on a `form_submit` event
|
||
in `dataLayer`. The hook has `onSuccess` (fires ONCE after a successful submit), and the plugin
|
||
provides the `pushDataLayer` helper — so the event goes out automatically, without a manual push
|
||
in every project:
|
||
|
||
```tsx
|
||
import { useContactForm, pushDataLayer } from '@intecion/ipal-kit/client'
|
||
|
||
const f = useContactForm({
|
||
submitAction,
|
||
onSuccess: (_result, v) => pushDataLayer('form_submit', { form_name: v.topic || 'contact' }),
|
||
})
|
||
```
|
||
|
||
In GTM: Data Layer Variable `DLV – form_name` (key `form_name`) + a custom event
|
||
trigger `form_submit`. **Consent is still gated by GTM** (`ad_storage`) — `pushDataLayer`
|
||
only emits the event, it does not bypass consent. `onSuccess` is wrapped in
|
||
try/catch — broken analytics will not block a successful submit. `pushDataLayer` is
|
||
SSR-safe and buffers the event when GTM has not loaded yet.
|
||
|
||
#### Managing from the PANEL (no code per form)
|
||
|
||
Instead of writing the event name/parameters in code, move them to the panel. Add
|
||
the analytics fields to the Forms collection:
|
||
|
||
```ts
|
||
// payload.config.ts
|
||
import { buildFormAnalyticsFields } from '@intecion/ipal-kit'
|
||
ipalKit({
|
||
forms: {
|
||
formOverrides: {
|
||
fields: ({ defaultFields }) => [...defaultFields, ...buildFormAnalyticsFields()],
|
||
},
|
||
},
|
||
})
|
||
```
|
||
|
||
The editor sets per form (panel labels are in English): **Event name**
|
||
(default `form_submit`) and **Event parameters** (key/value; a `$field` value
|
||
is taken from the form field, e.g. `form_name = $topic`). The field group is called
|
||
**Analytics (GTM / dataLayer)**. The front end reads it and emits automatically — one generic
|
||
line in the shared renderer works for ALL forms:
|
||
|
||
```tsx
|
||
import { useContactForm, formAnalyticsOnSuccess } from '@intecion/ipal-kit/client'
|
||
|
||
const f = useContactForm({
|
||
submitAction,
|
||
onSuccess: formAnalyticsOnSuccess(form.analytics), // form.analytics from the panel
|
||
})
|
||
```
|
||
|
||
Result: adding a tracked form or changing the event name/parameters = **panel only,
|
||
zero deploys**. An empty event name → nothing is pushed.
|
||
|
||
What stays in GTM (deliberately — it is also a panel, just Google's): the tag itself (Lead/Pixel),
|
||
its trigger on the event name and the `ad_storage` consent condition. The plugin provides the
|
||
event + the consent signal; GTM decides what to fire and when.
|
||
|
||
### resolveLocalized — no more getSafeString
|
||
|
||
Resolving a localized value (topics, labels) is one import, not a
|
||
copied `(v as any)[locale]`:
|
||
|
||
```ts
|
||
import { resolveLocalized } from '@intecion/ipal-kit' // root only (not in /client)
|
||
const label = resolveLocalized(topic.label, locale)
|
||
```
|
||
|
||
## TRAP — captcha fields
|
||
|
||
Turnstile injects a hidden `cf-turnstile-response` field. The plugin tolerates it
|
||
(does not reject it as `unknown_fields`) — because it handles Turnstile itself. You do not need to
|
||
filter it out on the client.
|
||
|
||
## 1.9.1 — ready action, form seed, type validation
|
||
|
||
- **`createSubmitAction({ getCachedPayload, headers })`** from `/server` replaces a hand-written `actions.ts`:
|
||
`export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`headers` from
|
||
`next/headers`, injected). Honeypot → `clientIp` → `submitForm` → text from Notifications;
|
||
result `{ success, message, reason?, field? }`.
|
||
- **Form seed** (`ipal-form/resources/seed-form.template.ts`): fields, confirmation, an email to the company
|
||
(address from the panel) and a confirmation to the customer (`{{email}}`), every language, idempotent. Mandatory.
|
||
- **Validation by the field type from the panel:** email = one address (no `a@x, b@y`, no CR/LF), select/radio
|
||
only values from the panel, numbers, checkbox `true/false`, objects and arrays rejected, control
|
||
and bidi characters removed. Error: `reason: 'validation'`, `kind: 'invalid_format'`, `field`.
|
||
- **Access:** submissions are read only by `editor`/`admin` (before: any account), deleted by `admin`;
|
||
the form's Emails tab (recipient addresses) is hidden in the public `GET /api/forms`.
|
||
|
||
## Turn off, override, extend
|
||
|
||
- **Turn off:** without the `forms` option the plugin does not wire the form-builder (no Forms / Form Submissions collections).
|
||
Single field types: `forms.fields.<type>: false`.
|
||
- **Override the collections:** `formOverrides` / `formSubmissionOverrides` — fields (the `fields` function), `labels`,
|
||
`admin`, `access`, `hooks`. The default submissions access (`create`: logged-in users, `read`: editor+, `delete`: admin)
|
||
is overridden by keys in `formSubmissionOverrides.access`; forms access (`create`/`update`/`delete`:
|
||
editor+, `read`: public) — in `formOverrides.access`. The Emails tab protection (`read`: editor+) is
|
||
applied to the default fields **before** `formOverrides.fields`, so you change it there.
|
||
- **Override a field type:** `forms.fields.<type>: <Block>` replaces the block; your own blocks with "Placeholder" /
|
||
time: `withPlaceholder`, `placeholderField`, `timeBlock`, `stepBlock`, `checkboxGroupBlock` (root).
|
||
- **Submit gates:** `submitForm` / `createSubmitAction` — `maxPerMinute` (`0` = no limit),
|
||
`turnstileOnConfigError`, `turnstileHostnames`, `consentFieldName`, `clientIp`, `honeypotField`;
|
||
site-wide consent field name: `forms.consentFieldName`; shared limit store: `setRateLimitStore`; missing IP: `setUnknownIpFactor`.
|
||
- **Check:** `POST /api/form-submissions` without a session = 403; a `user` account → `PATCH /api/forms/<id>` = 403;
|
||
submits without an IP header → past `maxPerMinute × 20` per minute (100 by default) you get `rate_limited`.
|
||
- **Emails:** `forms.beforeEmail` modifies emails (after the layout), `emailLayout: true` turns on the template.
|
||
- **Your own front end:** `BuilderForm` (`renderField`), `useBuilderForm`, pure logic (`splitSteps`,
|
||
`visibleFields`, `validateBuilderFields`…), `useForm` / `useContactForm`, validators, `buildFormsPlugin` (root).
|