Actions in forms
A form runs actions in response to its lifecycle triggers: submit it, tell the user, save a draft, reset. They are the action entries of Actions with a forms context, and a form config lists them as plain data.
Register, then reference
An action runs only when the engine has its registration, and the config refers to it by $type. engine.validateForm and defineForm check every action of the form and of its steps with parseActions, so an action whose $type is not registered, or whose options its schema refuses, is a config issue at its path, not a failure at submit time. The package ships two actions that work anywhere, and three that need the browser:
$type | Registration | Import from |
|---|---|---|
submit | SubmitActionRegistration | @schema-engine/forms |
show_notification | NotificationActionRegistration | @schema-engine/forms |
auto_save | AutoSaveActionRegistration | @schema-engine/forms/browser |
gtm_event | GTMActionRegistration | @schema-engine/forms/browser |
reset | ResetActionRegistration | @schema-engine/forms/browser |
The engine of the quick start registers none of them. engine.extend derives an engine that also registers these:
import { NotificationActionRegistration, SubmitActionRegistration } from '@schema-engine/forms';
import {
AutoSaveActionRegistration,
GTMActionRegistration,
ResetActionRegistration,
} from '@schema-engine/forms/browser';
import { engine as base } from './engine';
export const engine = base.extend({
actions: [
SubmitActionRegistration,
NotificationActionRegistration,
AutoSaveActionRegistration,
GTMActionRegistration,
ResetActionRegistration,
],
});Use createBrowserActionRegistrations({ storage, consent, confirm }) from @schema-engine/forms/browser to supply your own storage, consent tool or confirm dialog. Auto-save, GTM and Reset use browser storage, consent, window.confirm and the GTM data layer, which is why they are not in the package root.
Use them in a form
A form's actions run on every trigger that matches. The form below submits, tells the user and clears itself when the submission succeeds:
import { engine } from './actions-engine';
export const contact = engine.defineForm({
id: 'contact',
steps: [
{
id: 'message',
title: 'Your message',
elements: [{ $type: 'input', id: 'subject', name: 'subject', label: 'Subject' }],
},
],
actions: [
{
id: 'send',
$type: 'submit',
endpoint: '/api/contact',
method: 'POST',
successMessage: 'Thanks, we will reply soon.',
redirectUrl: '/thank-you',
},
{
id: 'confirm',
$type: 'show_notification',
message: 'Message sent',
variant: 'success',
triggers: ['form_submit_success'],
},
{ id: 'draft', $type: 'auto_save', storageKey: 'contact-draft', triggers: ['form_change'] },
{ id: 'track', $type: 'gtm_event', eventName: 'contact_sent', triggers: ['form_submit_success'] },
{ id: 'clear', $type: 'reset', triggers: ['form_submit_success'] },
],
});$type | Options | Default triggers (when triggers is omitted) |
|---|---|---|
submit | endpoint (required), method (POST, PUT, PATCH), successMessage, errorMessage, redirectUrl | form_submit |
show_notification | message (required), variant (success, error, warning, info), duration in ms (0 keeps it open) | form_submit_success, form_submit_error |
auto_save | storageKey, includeSensitive | form_change |
gtm_event | eventName (required), eventData, includeFormData | form_submit, form_submit_success |
reset | confirmMessage, resetToDefaults | form_submit_success |
Every entry also takes id, description, enabled and triggers. The engine checks id, enabled and triggers itself, so a registration's schema lists an action's own options only.
The submit action returns its redirectUrl in its result. Once the whole submission succeeded (every submit action and onSubmit), the runtime calls navigate with the last redirectUrl a successful submit action set. It defaults to location.assign in a browser and does nothing on a server; pass navigate to the renderer to use your router instead. Auto-save writes the form's values to browser storage on each trigger it answers, with form_change here. It does not debounce: it runs on every change.
Triggers
Form triggers
form_mount- The form's runtime mounts, onceform_change- The form's values changeform_submit- The submit actions run, after validation passed
Submit lifecycle
form_submit_start- Submit process begins, as the submission status becomessubmitting: after validation passed and before the submit actions. An invalid or overtaken submission never starts, so it runs none of the submit triggersform_submit_success- Submit completed successfully, after theonSubmitcallback resolvedform_submit_error- Submit failed: a submit action aborted, theonSubmitcallback rejected, or a trigger failedform_submit_complete- Submit finished (success or failure)
The order, with validation before them and the onSubmit callback inside, is in Form state.
Step triggers
step_leave- The current step is about to changestep_change- The current step changedstep_enter- A step became the current step
They fire in that order and only when the current step changes: by Next, Back or a jump, by the move to
the first step with an error after a failed or server-rejected submission, and by the move off a step that
became skipped. A reset fires none. A step action cannot block a move, since the step's validation is the
guard; if it fails, the failure is reported through onActionResults.
Configuring triggers
Actions can specify default triggers in their registration's metadata, or take triggers per entry, which replaces the defaults:
export const metadata = { name: 'Track', defaultTriggers: ['form_submit', 'form_submit_success'] };
export const perEntry = { id: 'custom-action', $type: 'submit', endpoint: '/api/forms', triggers: ['form_change'] };Step Actions
A step can declare its own actions. They are active while that step is the current
one: every trigger runs the form's actions first, then the current step's.
step_leavefires while the step being left is current, so it runs that step's actions, whether the user moves on with Next, goes back with Back, or jumps to another step.step_changeandstep_enterfire once the new step is current, so they run the entered step's actions. The first step is current on mount; it seesstep_enteronly when the user returns to it.- Completing the last step is a submission, not a step trigger. Track it with
form_submit_success.
{
"id": "preferences",
"title": "Preferences",
"elements": [],
"actions": [
{
"id": "preferences-view",
"$type": "gtm_event",
"eventName": "form_step_view",
"eventData": { "step_name": "preferences" },
"triggers": ["step_enter"]
}
]
}Creating custom actions
Use defineAction from @schema-engine/actions and specialize it with the forms runtime types:
import * as z from 'zod/mini';
import { defineAction, type ActionConfigBase } from '@schema-engine/actions';
import type { BuilderActionBaseContext, FormActionTrigger } from '@schema-engine/forms';
const defineFormAction = defineAction<BuilderActionBaseContext, FormActionTrigger>();
interface TrackSubmitConfig extends ActionConfigBase<'track_submit'> {
eventName: string;
}
export const trackAction = defineFormAction<TrackSubmitConfig>({
$type: 'track_submit',
schema: z.object({
eventName: z.string(),
}),
metadata: {
name: 'Track Submit',
defaultTriggers: ['form_submit_success'],
},
execute: async (context) => {
console.log(context.config.eventName, context.formData, context.formId);
return { success: true };
},
});The handler receives the forms base context enriched with config and trigger, so context.formData, context.formId, context.config and context.trigger are all strongly typed. Register it like the built-in ones, in createFormEngine({ actions: [trackAction] }).
The forms context
context.form, context.isValid, context.formData and context.errors exist only on the forms context. A handler of a different domain does not have them. Form action handlers receive formData, errors, form state and controller methods in addition to the action config and trigger. errors is keyed by dotted field path in both renderers, so a handler reads context.errors['address.street'].
Stop on failure
Return shouldContinue: false to stop the chain. In a form, this is how an action keeps the submit from going on:
import type { ActionExecutionResult } from '@schema-engine/actions';
import type { BuilderActionBaseContext } from '@schema-engine/forms';
export async function guard(context: BuilderActionBaseContext): Promise<ActionExecutionResult> {
if (!(await context.form.checkValidity())) {
return {
success: false,
error: 'Validation failed',
shouldContinue: false,
};
}
return { success: true };
}context.isValid is true while no validation error is recorded, so it is true on a pristine form even with an empty required field. context.form.checkValidity() validates the current values and resolves to whether the whole form passes. It records and shows no errors, and only the actions that call it pay for the validation. context.form.validate() validates, shows the errors and resolves { outcome: 'passed' | 'invalid' | 'overtaken' }. See Validity for the three reads.