Guides
Handling forms
Give a brick an action: its form works without JavaScript, and with it only the brick updates.
A brick can handle its own form: a contact form, a newsletter sign-up, a quote request. Give it an action, render a <ActionForm> in its component, and read the outcome from props.submission.
- Without JavaScript (Mortar's pages without JavaScript), the form is a plain post. The action runs on the server, and the browser comes back to the same page with the result, which the brick shows. A refresh doesn't post twice.
- With JavaScript (the admin, or an
interactivebrick, which hydrates on its own), the same form is sent in the background, and only that brick updates. The page doesn't reload.
The brick is the same either way. The example site (examples/site) has a working contact form at /contact.
The brick
import { ActionForm, defineBrick, fields } from '@mortar-kit/core';
import { Show } from 'solid-js';
type Result = { status: 'sent' } | { status: 'invalid'; values: Record<string, string> } | { status: 'failed' };
export const contactForm = defineBrick({
name: 'contact-form',
label: 'Contact form',
interactive: true,
schema: {
heading: fields.text({ label: 'Heading', default: 'Get in touch' }),
to: fields.text({ label: 'Send to', help: "Empty: the site's inbox.", private: true }),
},
async action({ form, data, context }): Promise<Result> {
const name = String(form.get('name') ?? '').trim();
const email = String(form.get('email') ?? '').trim();
const message = String(form.get('message') ?? '').trim();
if (!name || !email.includes('@') || !message) return { status: 'invalid', values: { name, email, message } };
const to = data.to || context.inbox;
if (!context.mailer || !to) return { status: 'failed' };
await context.mailer.send({ to, replyTo: email, subject: `Contact form: ${name}`, text: message });
return { status: 'sent' };
},
component: (props) => (
<section>
<h2>{props.data.heading}</h2>
<Show when={props.submission?.result?.status !== 'sent'} fallback={<p role="status">Thanks! We'll reply by email.</p>}>
<ActionForm>
<input name="name" required />
<input name="email" type="email" required />
<textarea name="message" required />
<button type="submit" disabled={props.submission?.pending}>Send</button>
</ActionForm>
</Show>
</section>
),
});
actiongets the postedform(untrusted: check every value), the entry'sdata, therequest, and the app'scontext. What it returns is the result: keep it plain JSON, and small, since without JavaScript it rides back in a cookie (about 4 kB).props.submissionis the entry's latest post:pending, thenresult, orerrorif the action threw. It's undefined until the form is sent.- Write
actionbeforecomponent, so the result has its type. interactive: truemakes the brick an island on public pages, so its form answers in place there too (see Islands).private: truekeeps the address out of what the island sends to the browser.
Server-only services
The brick's module also reaches the browser (in the admin, and in a brick that hydrates), so an action doesn't import the mailer, a database or a secret. The app passes them in context, and declares their types by augmenting ActionContext:
declare module '@mortar-kit/core' {
interface ActionContext {
mailer?: Mailer;
inbox?: string;
}
}
Wiring it up
Actions run through one server function in the app, which calls content.runAction with the reference and form the browser sent. That's the place for a per-client limit, since the form is public:
// src/server/content.ts
'use server';
export async function runBrickAction(ref: EntryRef, form: FormData | URLSearchParams): Promise<unknown> {
const request = getRequestEvent()?.request;
if (overLimit(request)) throw new Error('Too many form posts.');
return respond(await content.runAction(ref, form, { request, context: { mailer, inbox } }), { revalidate: '' });
}
Then the app tells Mortar where forms post and how to read results back, with BrickActionsContext. With Solid's router, a form action over that server function does both. It posts plainly without JavaScript (the result comes back in a one-time cookie the router reads), and in the background with it:
// src/actions.ts
const post = formAction(runBrickAction, 'mortar-brick-action');
export const brickActions: BrickActions = {
action: (ref) => post.with(ref),
useSubmission: (ref) => {
const all = useSubmissions(post, (input) => sameEntry(input[0], ref()));
return () => {
const last = all.at(-1);
return last && { pending: last.result === undefined && last.error === undefined, result: last.result, error: last.error };
};
},
};
// App.tsx: around the router
<BrickActionsContext value={brickActions}>
<Router>…</Router>
</BrickActionsContext>
On a public page without the router, an interactive brick's form goes through islandActions instead, which calls the same server function in the background. See Islands.
Finally, pass the document to PageView, so each form can name its entry: <PageView bricks={bricks} entries={page.entries ?? []} doc={{ collection: 'pages', id: page.id }} />. The admin preview does this itself. It doesn't send forms, so editors can click around in them.
ActionFormfunction
import { ActionForm } from '@mortar-kit/core'
function ActionForm(props: ActionFormProps): ElementA form that posts to its brick's action. Use it in the component of a
brick that declares one. It's a plain <form method="post">, so it works
without JavaScript; the router (or whatever the app's BrickActions
uses) can take over the submit when the page has scripts, and on an
island BrickActions.submit sends it in the background.
Parameters
props: ActionFormProps
Returns
Element
BrickActionsinterface
import { BrickActions } from '@mortar-kit/core'
interface BrickActionsHow the app connects brick forms to the server. Provide it with
BrickActionsContext around the site; without it, a <ActionForm>
renders but doesn't post anywhere.
Properties
action: (ref: EntryRef) => string | SerializableAttributeValueThe
actionattribute of an entry's form: the URL (or the router's form action) its post goes to.useSubmission: (ref: () => EntryRef) => () => Submission<unknown> | undefinedThe entry's latest submission, for its component. Called once per entry while rendering (hooks are fine);
refis an accessor because an entry can move to another document in the admin preview.submit?: (ref: EntryRef, form: FormData) => voidSends an entry's form in the background. When present,
<ActionForm>stops the browser's own post and calls it; without it, the post goes toaction(ref)(where a router may take it over).islandActionshas it.
ActionInputinterface
import { ActionInput } from '@mortar-kit/core'
interface ActionInput<D>What a brick's action receives.
Properties
form: FormDataThe posted form. Untrusted: check every value.
data: DThe entry's stored data, read on the server (never sent by the browser), normalized.
request: Request | undefinedThe request the post arrived in, when the app passes it (e.g. for a per-client limit).
context: ActionContextThe app's server-side services (see
ActionContext).
Submissioninterface
import { Submission } from '@mortar-kit/core'
interface Submission<R>A form post to a brick's action, as its component sees it.
Properties
pending: booleanTrue while the post is in flight (only with JavaScript; a plain post reloads the page).
result?: RWhat the action returned.
error?: unknownWhat the action threw, if it threw (in production, a generic error).