Forms: conditional fields and steps (Show only when)
Every form block (built-in, Checkbox group, Step, message) gets a showWhen group: visible only when another field has one of the given values. A hidden Step drops out with its fields; browser and server share visibleFields, so a hidden field is neither required nor stored. GDPR consent is always enforced. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -11,6 +11,9 @@ import type { Block, Field } from 'payload'
|
||||
*
|
||||
* Plain English labels (the panel is EN). Rendered by BuilderForm /
|
||||
* useBuilderForm, validated by submitForm like every other field.
|
||||
*
|
||||
* Every block (built-in ones too, see withShowWhen) also gets "Show only when"
|
||||
* (`showWhen`) — conditional visibility, evaluated by visibleFields.
|
||||
*/
|
||||
|
||||
const name: Field = {
|
||||
@@ -24,7 +27,41 @@ const label: Field = { name: 'label', type: 'text', admin: { width: '50%' }, lab
|
||||
const width: Field = { name: 'width', type: 'number', admin: { width: '50%' }, label: 'Field width (percentage)' }
|
||||
const required: Field = { name: 'required', type: 'checkbox', admin: { width: '50%' }, label: 'Required' }
|
||||
|
||||
export const stepBlock: Block = {
|
||||
/**
|
||||
* "Show only when": the field — or, on a Step, the whole step — appears only
|
||||
* when another field has one of the given values. Evaluated by visibleFields
|
||||
* in the browser and again on the server (hidden fields are neither required nor stored).
|
||||
*/
|
||||
export const showWhenField: Field = {
|
||||
name: 'showWhen',
|
||||
type: 'group',
|
||||
admin: {
|
||||
description:
|
||||
'Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".',
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
type: 'row',
|
||||
fields: [
|
||||
{ name: 'field', type: 'text', admin: { description: 'Technical name of another field.', width: '50%' }, label: 'Field name' },
|
||||
{
|
||||
name: 'values',
|
||||
type: 'text',
|
||||
admin: { description: 'Comma-separated option values. Empty = when that field is filled in or ticked.', width: '50%' },
|
||||
label: 'Values',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
label: 'Show only when',
|
||||
}
|
||||
|
||||
/** Adds "Show only when" at the end of a block's fields. */
|
||||
export function withShowWhen<B extends Block>(block: B): B {
|
||||
return { ...block, fields: [...block.fields, showWhenField] }
|
||||
}
|
||||
|
||||
const stepBase: Block = {
|
||||
slug: 'step',
|
||||
fields: [
|
||||
{
|
||||
@@ -42,7 +79,7 @@ export const stepBlock: Block = {
|
||||
labels: { plural: 'Steps', singular: 'Step' },
|
||||
}
|
||||
|
||||
export const checkboxGroupBlock: Block = {
|
||||
const checkboxGroupBase: Block = {
|
||||
slug: 'checkboxGroup',
|
||||
fields: [
|
||||
{ type: 'row', fields: [name, label] },
|
||||
@@ -72,3 +109,6 @@ export const checkboxGroupBlock: Block = {
|
||||
],
|
||||
labels: { plural: 'Checkbox groups', singular: 'Checkbox group' },
|
||||
}
|
||||
|
||||
export const stepBlock: Block = withShowWhen(stepBase)
|
||||
export const checkboxGroupBlock: Block = withShowWhen(checkboxGroupBase)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BuilderField, BuilderFormTexts, BuilderStep } from './builderTypes.js'
|
||||
import type { BuilderField, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
|
||||
|
||||
import { NON_INPUT_TYPES } from './builderTypes.js'
|
||||
import { isEmail } from './validators.js'
|
||||
@@ -19,16 +19,24 @@ export function inputFields(fields: BuilderField[] | null | undefined): ({ name:
|
||||
/**
|
||||
* Splits the field list at `step` blocks. Fields before the first Step form
|
||||
* the first screen; a form without Steps is one screen.
|
||||
*
|
||||
* `isShown` (e.g. membership in visibleFields) leaves hidden fields — and a
|
||||
* hidden Step with everything under it — out, while `index` stays the field's
|
||||
* position in the full list (RenderForm renders `message` blocks by it).
|
||||
*/
|
||||
export function splitSteps(fields: BuilderField[] | null | undefined): BuilderStep[] {
|
||||
export function splitSteps(fields: BuilderField[] | null | undefined, isShown?: (field: BuilderField) => boolean): BuilderStep[] {
|
||||
const steps: BuilderStep[] = []
|
||||
let current: BuilderStep | null = null
|
||||
let skipping = false
|
||||
;(fields ?? []).forEach((field, index) => {
|
||||
if (field.blockType === 'step') {
|
||||
skipping = isShown ? !isShown(field) : false
|
||||
if (skipping) {return}
|
||||
current = { description: field.description ?? undefined, fields: [], index: steps.length, title: field.title ?? undefined }
|
||||
steps.push(current)
|
||||
return
|
||||
}
|
||||
if (skipping || (isShown && !isShown(field))) {return}
|
||||
if (!current) {
|
||||
current = { fields: [], index: 0 }
|
||||
steps.push(current)
|
||||
@@ -40,6 +48,60 @@ export function splitSteps(fields: BuilderField[] | null | undefined): BuilderSt
|
||||
return (kept.length ? kept : [{ fields: [], index: 0 }]).map((s, i) => ({ ...s, index: i }))
|
||||
}
|
||||
|
||||
const isBlankValue = (v: unknown) =>
|
||||
v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)
|
||||
|
||||
/** The minimum a field needs for conditional visibility — panel docs on the server, BuilderField on the client. */
|
||||
type ConditionalField = { blockType?: null | string; name?: null | string; showWhen?: FieldCondition | null }
|
||||
|
||||
const conditionValues = (condition: FieldCondition | null | undefined) =>
|
||||
(condition?.values ?? '').split(',').map((v) => v.trim()).filter(Boolean)
|
||||
|
||||
/**
|
||||
* The fields (Steps and messages included) a visitor sees for the given values,
|
||||
* in panel order. A field is hidden when its own "Show only when" fails, when
|
||||
* its Step's condition fails (the whole step goes), or when the field its
|
||||
* condition points at is itself hidden. A condition naming a field that doesn't
|
||||
* exist hides the field — a typo shows up in the preview instead of passing silently.
|
||||
*
|
||||
* Shared by the browser (useBuilderForm: which steps and fields to show and
|
||||
* validate) and the server (validateSubmission: hidden fields are neither
|
||||
* required nor stored), so both agree on what was on screen.
|
||||
*/
|
||||
export function visibleFields<F extends ConditionalField>(fields: F[] | null | undefined, values: Record<string, unknown>): F[] {
|
||||
const list = fields ?? []
|
||||
const byName = new Map(list.filter((f) => f.name && f.blockType !== 'step').map((f) => [f.name as string, f]))
|
||||
const stepOf = new Map<F, F | undefined>()
|
||||
let currentStep: F | undefined
|
||||
for (const field of list) {
|
||||
if (field.blockType === 'step') {currentStep = field}
|
||||
stepOf.set(field, field.blockType === 'step' ? undefined : currentStep)
|
||||
}
|
||||
|
||||
const cache = new Map<F, boolean>()
|
||||
const met = (condition: FieldCondition | null | undefined, seen: Set<F>): boolean => {
|
||||
const ref = condition?.field?.trim()
|
||||
if (!ref) {return true}
|
||||
const target = byName.get(ref)
|
||||
if (!target || seen.has(target) || !visible(target, seen)) {return false}
|
||||
const value = values[ref]
|
||||
const wanted = conditionValues(condition)
|
||||
if (wanted.length === 0) {return !isBlankValue(value)}
|
||||
if (Array.isArray(value)) {return value.some((v) => wanted.includes(String(v)))}
|
||||
return value != null && value !== '' && wanted.includes(String(value as boolean | number | string))
|
||||
}
|
||||
const visible = (field: F, seen: Set<F> = new Set()): boolean => {
|
||||
const cached = cache.get(field)
|
||||
if (cached !== undefined) {return cached}
|
||||
const nextSeen = new Set(seen).add(field)
|
||||
const step = stepOf.get(field)
|
||||
const result = (!step || met(step.showWhen, nextSeen)) && met(field.showWhen, nextSeen)
|
||||
cache.set(field, result)
|
||||
return result
|
||||
}
|
||||
return list.filter((field) => visible(field))
|
||||
}
|
||||
|
||||
/** Starting values: checkbox → boolean, checkboxGroup → string[], the rest → string. */
|
||||
export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record<string, unknown> {
|
||||
return Object.fromEntries(
|
||||
@@ -52,8 +114,7 @@ export function initialBuilderValues(fields: BuilderField[] | null | undefined):
|
||||
)
|
||||
}
|
||||
|
||||
const isBlank = (v: unknown) =>
|
||||
v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)
|
||||
const isBlank = isBlankValue
|
||||
|
||||
/** Errors for the given fields (one message per field), empty object = valid. */
|
||||
export function validateBuilderFields(
|
||||
|
||||
@@ -6,6 +6,13 @@ import type { FormAnalyticsConfig } from './formAnalytics.js'
|
||||
*/
|
||||
export type BuilderOption = { label?: null | string; value: string }
|
||||
|
||||
/**
|
||||
* "Show only when" of a field or a Step (panel group `showWhen`): visible only
|
||||
* when the field named `field` has one of `values` (comma-separated). Empty
|
||||
* `values` = when that field is filled in / ticked. Empty `field` = always.
|
||||
*/
|
||||
export type FieldCondition = { field?: null | string; values?: null | string }
|
||||
|
||||
export type BuilderField = {
|
||||
blockName?: null | string
|
||||
/** text · textarea · email · number · date · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
|
||||
@@ -23,6 +30,8 @@ export type BuilderField = {
|
||||
options?: BuilderOption[] | null
|
||||
placeholder?: null | string
|
||||
required?: boolean | null
|
||||
/** Conditional visibility — see FieldCondition. On a Step it hides the whole step. */
|
||||
showWhen?: FieldCondition | null
|
||||
/** step */
|
||||
title?: null | string
|
||||
width?: null | number
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
import type { Field, Plugin } from 'payload'
|
||||
import type { Block, Field, Plugin } from 'payload'
|
||||
|
||||
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
|
||||
import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-form-builder'
|
||||
|
||||
import type { FormsOption } from './types.js'
|
||||
|
||||
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
|
||||
import { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
|
||||
import { checkboxGroupBlock, stepBlock, withShowWhen } from './builderBlocks.js'
|
||||
|
||||
type AccessArgs = { req: { user?: unknown } }
|
||||
|
||||
/** A built-in form-builder block with "Show only when" added (full block — form-builder merges arrays by replacing). */
|
||||
const builtin = (key: 'checkbox' | 'date' | 'email' | 'message' | 'number' | 'radio' | 'select' | 'text' | 'textarea') =>
|
||||
withShowWhen(builtinBlocks[key] as Block)
|
||||
|
||||
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
|
||||
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
|
||||
/**
|
||||
@@ -57,20 +61,22 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
|
||||
// panel choices only — a form uses what the editor adds, nothing changes on
|
||||
// existing forms. Switch any off with forms.fields.<type>: false.
|
||||
fields: {
|
||||
checkbox: true,
|
||||
// every block carries "Show only when" (showWhen) — conditional fields and steps
|
||||
checkbox: builtin('checkbox'),
|
||||
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
|
||||
date: true,
|
||||
email: true,
|
||||
message: true,
|
||||
number: true,
|
||||
date: builtin('date'),
|
||||
email: builtin('email'),
|
||||
message: builtin('message'),
|
||||
number: builtin('number'),
|
||||
payment: false,
|
||||
radio: true,
|
||||
select: true,
|
||||
radio: builtin('radio'),
|
||||
select: builtin('select'),
|
||||
step: forms.fields?.step === false ? false : stepBlock,
|
||||
text: true,
|
||||
textarea: true,
|
||||
text: builtin('text'),
|
||||
textarea: builtin('textarea'),
|
||||
...Object.fromEntries(
|
||||
Object.entries(forms.fields ?? {}).filter(([k]) => k !== 'checkboxGroup' && k !== 'step'),
|
||||
// `true` keeps ipal's block (with "Show only when"); false / an object override it
|
||||
Object.entries(forms.fields ?? {}).filter(([k, v]) => k !== 'checkboxGroup' && k !== 'step' && v !== true),
|
||||
),
|
||||
},
|
||||
...(forms.redirectRelationships
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Panel field types: step-by-step forms + multiple choice (enabled by default).
|
||||
export { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
|
||||
// Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm.
|
||||
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js'
|
||||
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './builderTypes.js'
|
||||
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
|
||||
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep, FieldCondition } from './builderTypes.js'
|
||||
export { formAnalyticsOnSuccess } from './formAnalytics.js'
|
||||
export type { FormAnalyticsConfig } from './formAnalytics.js'
|
||||
// Panel-managed form analytics: fields (config-time) + onSuccess helper (client).
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { BuilderField, BuilderFormAction, BuilderFormDoc, BuilderFormTexts,
|
||||
|
||||
import { safeHref } from '../links/resolveLinkHref.js'
|
||||
import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js'
|
||||
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js'
|
||||
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
|
||||
import { formAnalyticsOnSuccess } from './formAnalytics.js'
|
||||
import { useForm } from './useForm.js'
|
||||
|
||||
@@ -42,8 +42,8 @@ export type UseBuilderFormOptions = {
|
||||
*/
|
||||
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts }: UseBuilderFormOptions) {
|
||||
const fields = useMemo(() => form.fields ?? [], [form.fields])
|
||||
const steps = useMemo(() => splitSteps(fields), [fields])
|
||||
const inputs = useMemo(() => inputFields(fields), [fields])
|
||||
// Fields behind a failed "Show only when" are neither shown, validated nor sent.
|
||||
const visibleInputs = useCallback((values: Record<string, unknown>) => inputFields(visibleFields(fields, values)), [fields])
|
||||
const [stepIndex, setStepIndex] = useState(0)
|
||||
const [resultMessage, setResultMessage] = useState<null | string>(null)
|
||||
const ts = useOptionalTurnstile()
|
||||
@@ -52,15 +52,16 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
const serverFieldError = useRef<{ field: string; message: string } | null>(null)
|
||||
const submitAction = useCallback(
|
||||
async (values: Record<string, unknown>, token?: string) => {
|
||||
const result = await action(values, token)
|
||||
const shown = new Set(visibleInputs(values).map((field) => field.name))
|
||||
const result = await action(Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name))), token)
|
||||
if (result.success) {setResultMessage(result.message ?? null)}
|
||||
else if (result.field) {serverFieldError.current = { field: result.field, message: result.message ?? texts.validation.replace('{field}', result.field) }}
|
||||
return result
|
||||
},
|
||||
[action, texts.validation],
|
||||
[action, texts.validation, visibleInputs],
|
||||
)
|
||||
|
||||
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(inputs, values, texts), [inputs, texts])
|
||||
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts])
|
||||
|
||||
const f = useForm<Record<string, unknown>>({
|
||||
errorFallback: texts.error,
|
||||
@@ -78,6 +79,11 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
validate,
|
||||
})
|
||||
const { setErrors, setTurnstileToken } = f
|
||||
// Steps follow the answers: a Step whose condition fails drops out, later steps renumber.
|
||||
const steps = useMemo(() => {
|
||||
const shown = new Set(visibleFields(fields, f.values))
|
||||
return splitSteps(fields, (field) => shown.has(field))
|
||||
}, [fields, f.values])
|
||||
|
||||
// Turnstile token lives in the provider; the engine needs it at submit.
|
||||
useEffect(() => setTurnstileToken(ts.token), [ts.token, setTurnstileToken])
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import type { FieldCondition } from './builderTypes.js'
|
||||
|
||||
import { visibleFields } from './builderLogic.js'
|
||||
|
||||
/** A form-builder field, trimmed to what validation needs. */
|
||||
type FormField = {
|
||||
blockType?: string
|
||||
@@ -11,6 +15,8 @@ type FormField = {
|
||||
/** select / radio / checkboxGroup choices defined in the panel. */
|
||||
options?: { value?: unknown }[] | null
|
||||
required?: boolean | null
|
||||
/** "Show only when" — hidden fields are neither required nor stored. */
|
||||
showWhen?: FieldCondition | null
|
||||
}
|
||||
|
||||
type FormDoc = {
|
||||
@@ -171,10 +177,15 @@ export async function validateSubmission(
|
||||
typeof f.name === 'string' && !NON_DATA_BLOCKS.has(f.blockType ?? ''),
|
||||
)
|
||||
const known = new Map(fields.map((f) => [f.name, f]))
|
||||
// Same rule as the browser: what a failed "Show only when" hid wasn't on screen.
|
||||
const shown = new Set(visibleFields(form.fields, data))
|
||||
|
||||
const cleaned: Record<string, unknown> = {}
|
||||
|
||||
for (const field of fields) {
|
||||
// Hidden by a condition: not required, not stored. The consent gate never hides —
|
||||
// an editor can't switch GDPR consent off with a condition.
|
||||
if (!shown.has(field) && field.name !== consentFieldName) {continue}
|
||||
const value = data[field.name]
|
||||
const isBlank =
|
||||
value == null ||
|
||||
|
||||
Reference in New Issue
Block a user