Submit, notify and reset
A form often does more than call onSubmit: it sends the values, tells the visitor how it went, and clears itself. This example is a newsletter signup that does those three things as actions listed in its config. The actions are data, so a server can send them with the form. Each one runs on the moment it names, form_submit_success after the request worked and form_submit_error after it failed, and they run in the order they are listed.
Install
For React:
pnpm add @schema-engine/forms @schema-engine/forms-react @schema-engine/layout react react-dom zodThe React file imports the fields that the shadcn registry installs. Run pnpm dlx shadcn@latest add schema-engine/schema-engine/schema-form once, as the Contact form explains.
For Radiant:
pnpm add @schema-engine/forms @schema-engine/forms-radiant @schema-engine/layout @ecopages/radiant-ui @ecopages/radiant @ecopages/jsx @ecopages/signals zodCopy the files below into one folder. Radiant also needs its JSX setup and stylesheets: Forms Radiant: installation and quick start. React needs "jsx": "react-jsx" in tsconfig.json.
See it
Submit an empty form to see the message. Enter an email and submit: the action sends it to a mock endpoint, a notification appears, and the field clears.
The demos use this site's styled widgets, not the example's own files, and send to no real server: a valid submit shows the notice the config names.
The config
actions is part of the config. submit sends the values to endpoint, and by default answers form_submit. The two notifications and the reset name their triggers. If the request fails, the submit action stops the chain, form_submit_error runs, and the error notification tells the visitor. The values stay in the field, so they can try again. See Actions in forms for every trigger.
import type { FormConfig } from '@schema-engine/forms';
/**
* A newsletter signup that sends itself, tells the visitor how it went and clears itself.
*
* @remarks
* `actions` are plain data, so the server could send them with the rest of the config. Each entry runs on the
* triggers it names, in the order it is listed: `submit` answers `form_submit` by default, and the other entries
* run after it succeeded or failed. The values passed validation before any of them ran.
*/
export const newsletter: FormConfig = {
id: 'newsletter',
title: 'Get the monthly update',
steps: [
{
id: 'signup',
title: 'Get the monthly update',
elements: [
{
$type: 'input',
id: 'email',
name: 'email',
label: 'Email',
inputType: 'email',
rules: [
{ $type: 'required', message: 'Enter your email' },
{ $type: 'email', message: 'Enter a valid email address' },
],
},
{ $type: 'submit', id: 'subscribe', name: 'subscribe', label: 'Subscribe' },
],
},
],
actions: [
{ id: 'send', $type: 'submit', endpoint: '/api/subscriptions', method: 'POST' },
{
id: 'thanks',
$type: 'show_notification',
message: 'You are subscribed. Look out for the next update.',
variant: 'success',
triggers: ['form_submit_success'],
},
{ id: 'clear', $type: 'reset', resetToDefaults: true, triggers: ['form_submit_success'] },
{
id: 'sorry',
$type: 'show_notification',
message: 'We could not subscribe you. Try again in a moment.',
variant: 'error',
triggers: ['form_submit_error'],
},
],
};Register the actions
An action runs only when the engine has its registration, and the config refers to it by $type. A config that names an action nobody registered is a config issue at its path, not a failure at submit time. This file registers the three the config uses:
SubmitActionRegistrationsends the values with the engine'sfetch, as form data, and expects JSON back.show_notificationis built withnotificationPlugin. The package's ownNotificationActionRegistrationonly logs, because the package cannot know how an app shows a message. The function you pass here is where an app calls its toast library: this example publishes the message on anEventTargetthat the form's file listens to.ResetActionRegistrationclears the form. It lives in@schema-engine/forms/browser, because it uses browser storage.
import { SubmitActionRegistration, notificationPlugin } from '@schema-engine/forms';
import { ResetActionRegistration } from '@schema-engine/forms/browser';
/** What a `show_notification` action announces. */
export interface Notice {
message: string;
variant: 'success' | 'error' | 'warning' | 'info';
}
/**
* Where notifications go. A real app hands them to its toast library here instead.
*
* @remarks
* `NotificationActionRegistration`, the package's own registration, only logs, because the package cannot know
* how an app shows a message. `notificationPlugin` takes the one function that does.
*/
export const notices = new EventTarget();
const NotificationRegistration = notificationPlugin({
onNotification: (message, variant) => {
notices.dispatchEvent(new CustomEvent<Notice>('notice', { detail: { message, variant } }));
},
});
/**
* The actions the config names, each registered by hand: an action runs only when its engine has its registration.
*
* @remarks
* `submit` sends the values to `endpoint` with the engine's `fetch`, as form data, and expects JSON back.
* `show_notification` runs {@link notices}. `reset` clears the form, and lives in `@schema-engine/forms/browser`
* because it uses browser storage.
*/
export const actions = [SubmitActionRegistration, NotificationRegistration, ResetActionRegistration];The renderer
Each tab builds an engine with the actions and renders the config. The status line shows the last notification: the React file reads it from notices in an effect, and the Radiant file has a showNotices function that does the same for the page it is on. React registers the installed fields, and Radiant ships its own.
import { useEffect, useState } from 'react';
import { createFormEngine } from '@schema-engine/forms';
import { FormRenderer } from '@schema-engine/forms-react';
import { actions, notices, type Notice } from './actions';
import { newsletter } from './config';
import { schemaFormRegistrations } from '@/components/schema-engine/forms/registrations';
export const engine = createFormEngine({ elements: schemaFormRegistrations, actions });
/** The form, and a status line that shows what the notification actions announce. */
export function Newsletter() {
const [message, setMessage] = useState('');
useEffect(() => {
const show = (event: Event) => setMessage((event as CustomEvent<Notice>).detail.message);
notices.addEventListener('notice', show);
return () => notices.removeEventListener('notice', show);
}, []);
return (
<>
<FormRenderer engine={engine} config={newsletter} />
<output>{message}</output>
</>
);
}import { createRadiantFormEngine, FormRenderer, schemaFormRegistrations } from '@schema-engine/forms-radiant';
import { actions, notices, type Notice } from './actions';
import { newsletter } from './config';
export const engine = createRadiantFormEngine({ elements: schemaFormRegistrations, actions });
/** The form, and a status line that {@link showNotices} fills. */
export function Newsletter() {
return (
<>
<FormRenderer engine={engine} config={newsletter} />
<output data-notice />
</>
);
}
/** Shows what the notification actions announce in the status line under `root`, until the returned function runs. */
export function showNotices(root: ParentNode): () => void {
const show = (event: Event) => {
const status = root.querySelector('[data-notice]');
if (status) status.textContent = (event as CustomEvent<Notice>).detail.message;
};
notices.addEventListener('notice', show);
return () => notices.removeEventListener('notice', show);
}What the tests check
The example's tests render both files in a browser. An invalid email shows its message, sends nothing and notifies nobody. A valid email sends form data to /api/subscriptions, announces the success and clears the field. A 500 announces the error and keeps what was typed.
Take it further
- Run more actions: Actions in forms lists auto-save, analytics events and how to write your own.
- Show the server's answer on the fields instead: Contact form and Server errors.
- The action engine without a form: A checkout workflow.