Steps
A long form can show one step at a time. On the canvas, drag in a New step where a step should start and give it a title; the fields before the first one make the first step. With the first step field, a start block appears at the top of the canvas. It sets the first step's title, the labels of the previous and next buttons, and the progress: every step by its title (the default), a bar with "Step 2 of 3", or none.
On the site, the next button checks the step's fields before moving on, and a step whose fields the conditions all hide is skipped. In the list of steps, a step the visitor has done is a link back to it; forward goes through the next button only, so every step is checked again. The submit button and a captcha come after the last step, where the next button was. The server checks every answer when the form is sent, as always, and the form opens again on the step with the first error. Without JavaScript every step shows, one below the other, and the form works as one.
In code, a form type starts a step with StepField, and sets what the start
block would in stepSettings():
use VanOns\FilamentFormBuilder\Classes\StepSettings;
use VanOns\FilamentFormBuilder\Filament\FormBuilder\Fields\StepField;
public function fields(): array
{
return [
TextInputField::make('naam')->label('Naam')->required(),
StepField::make('motivatie_stap')->title('Motivatie'),
TextAreaField::make('motivatie')->label('Motivatie'),
SubmitField::make('verstuur'),
];
}
public function stepSettings(): array
{
return StepSettings::normalize(['title' => 'Over jou', 'progress' => 'bar']);
}Checking a step on the server
The browser checks what an editor can set: required, an email address, a
length. A rule only the server knows, such as unique or exists, is checked
when the form is sent, and the form then opens again on that step. A form type
can have the server check each step before the visitor moves on:
public function fields(): array
{
return [
EmailField::make('email')->label('Email')->required()->rules(['unique:users,email']),
StepField::make('profiel')->title('Your profile'),
// ...
];
}
public function validatesSteps(): bool
{
return true;
}validate_steps in the config does the same for every form type.
The next button then posts the answers so far to the form's own route with
Laravel Precognition, which checks the
step's fields only and stores nothing. A message shows under its field and the
visitor stays on the step. Uploads only go along with the form itself, and
when the server cannot be reached the visitor moves on: the form is checked in
full once it is sent anyway. These checks have a limit of their own, 60 a
minute per visitor, apart from rate_limit_per_hour, and the spam traps wait
for the form itself.
The steps render through components/steps, the progress through
components/steps/progress-steps or progress-bar; the classes are under
Styling forms on the site. A components/form of
your own shows the steps with
<x-filament-form-builder::steps :form="$form" /> where $form->hasSteps().
The answers of a submission are grouped per step on its page.
Steps in a front end of your own
resources/js/steps.js holds the same logic for React, Vue or anything else,
typed by steps.d.ts, next to conditions.js. Hand the page the steps with
the fields:
'steps' => $form->getStepKeys(), // per step its title and the keys of its fields| Function | Gives |
|---|---|
visibleSteps(steps, hidden) | The indexes of the steps that show, given the keys hiddenKeys() hides |
nextStep(steps, hidden, current) | The next step that shows, or null on the last |
previousStep(steps, hidden, current) | The previous step that shows, or null on the first |
firstStepWithError(steps, errorKeys) | The step to open after the server turned the form away |
progress(steps, hidden, current) | { number, total, percent } among the steps that show |
reportStep(element) | Shows why a step's fields cannot be left yet; true when they can |
validateOnly(keys) | The Precognition-Validate-Only header for checking a step's keys |
Keep every step mounted and hide the others with hidden: <Form> posts what
is in the form element, so a step that is not rendered loses its answers. Keep a
captcha laid out until the last step, with visibility: hidden rather than
hidden: Turnstile does not draw itself in an element that is not displayed. Give
the form noValidate, or the browser stops at a required field in a step the
visitor has not seen yet, and check the step with reportStep() instead:
import { Form } from '@inertiajs/react'
import { useEffect, useRef, useState } from 'react'
import { hiddenKeys, readValues } from '@form-builder/conditions'
import { firstStepWithError, nextStep, previousStep, progress, reportStep } from '@form-builder/steps'
export default function ApplicationForm({ form, errors }) {
const [hidden, setHidden] = useState(() => new Set<string>())
const [current, setCurrent] = useState(0)
const fieldsets = useRef<HTMLFieldSetElement[]>([])
const following = nextStep(form.steps, hidden, current)
const before = previousStep(form.steps, hidden, current)
const { number, total } = progress(form.steps, hidden, current)
useEffect(() => {
const step = firstStepWithError(form.steps, Object.keys(errors))
step !== null && setCurrent(step)
}, [errors])
return (
<Form
action={`/filament-form-builder/${form.id}/submit`}
method="post"
noValidate
onChange={(event) => setHidden(hiddenKeys(form.conditions, readValues(event.currentTarget)))}
>
<p>Step {number} of {total}</p>
{form.steps.map((step, index) => (
<fieldset key={index} hidden={index !== current} ref={(element) => { fieldsets.current[index] = element }}>
{step.title && <legend>{step.title}</legend>}
{/* the fields of step.keys */}
</fieldset>
))}
{before !== null && <button type="button" onClick={() => setCurrent(before)}>Previous</button>}
{following === null
? <button type="submit">Send</button>
: <button type="button" onClick={() => reportStep(fieldsets.current[current]) && setCurrent(following)}>Next</button>}
</Form>
)
}When the form type checks its steps on the server
($form->getType()->validatesSteps()), post the answers so far before moving
on, without the uploads. A 204 means the step is fine, a 422 has the errors:
import { validateOnly } from '@form-builder/steps'
async function checkStep(form: HTMLFormElement, keys: string[]): Promise<Record<string, string[]>> {
const body = new FormData(form)
for (const [name, value] of [...body]) {
if (value instanceof File) {
body.delete(name)
}
}
const response = await fetch(form.action, {
method: 'POST',
body,
headers: { Accept: 'application/json', Precognition: 'true', 'Precognition-Validate-Only': validateOnly(keys) },
})
return response.status === 422 ? (await response.json()).errors : {}
}