<Form>
A plain HTML form that submits through Inertia. It keeps no field state: on submit it reads the fields from the DOM by their name, sends them, and yields the request's state, errors and methods to its block.
import { Form } from 'inertia-ember';
<template>
<Form @action='/posts' @method='post' as |form|>
<input name='title' />
{{#if form.errors.title}}<p>{{form.errors.title}}</p>{{/if}}
<button disabled={{form.processing}}>Publish</button>
</Form>
</template>The server answers the way it answers any Inertia form: a redirect to the next page, or the same page with validation errors, which fill form.errors.
Arguments
| Argument | Type | Default | Description |
|---|---|---|---|
@action | string | UrlMethodPair | '' | Where to send it: a URL, or a { url, method } pair whose method wins over @method. Also the Precognition endpoint. |
@method | Method | Uppercase<Method> | 'get' | get, post, put, patch, delete or query, in either case. GET puts the fields in the query string. |
@headers | Record<string, string> | {} | Request headers, also sent with Precognition validations. |
@transform | (data: TForm) => Record<string, FormDataConvertible> | Change the data read from the DOM before it's sent (and validated). | |
@errorBag | string | null | null | Read errors from this bag of the response. |
@queryStringArrayFormat | 'brackets' | 'indices' | 'brackets' | How arrays are written into a GET query string. |
@showProgress | boolean | true | Show the progress bar during the visit. |
@invalidateCacheTags | string | string[] | [] | Prefetch cache tags to invalidate with this request. |
@options | FormComponentOptions | More visit options: preserveScroll, preserveState, preserveUrl, replace, only, except, reset, viewTransition, async. They're applied last. | |
@resetOnSuccess | boolean | string[] | false | After a success, put every field (true) or the named ones back to their defaults. |
@resetOnError | boolean | string[] | false | The same after validation errors: @resetOnError={{array 'password'}}. |
@setDefaultsOnSuccess | boolean | false | After a success, the current values become the defaults (for isDirty and reset). |
@onSubmitComplete | (form: { reset, defaults }) => void | Runs after a success, after @onSuccess and before @resetOnSuccess. | |
@disableWhileProcessing | boolean | false | Make the form inert while the request is in flight. |
@cancelOnUnmount | boolean | false | Cancel the request in flight when the form leaves the page. |
@optimistic | (props: PageProps, data: TForm) => Partial<PageProps> | void | Change the page's props before the server answers; rolled back if the request fails. | |
@component | string | Render this page component right away, an Inertia instant visit. | |
@instant | boolean | false | With a @action pair that names a component, render that component right away. |
@validationTimeout | number | 1500 | Precognition's debounce, in ms. |
@validateFiles | boolean | false | Send files in Precognition validations. |
@withAllErrors | boolean | null | the form.withAllErrors default (false) | Keep every message per field, so each error is a list. |
It also takes the visit callbacks: @onBefore, @onBeforeUpdate, @onStart, @onProgress, @onSuccess, @onError, @onCancel, @onFinish, @onHttpException, @onNetworkError, @onFlash and @onCancelToken. They're called as for any visit, and returning false from @onBefore cancels it.
The visit options and callbacks are Inertia core's; see manual visits in its docs. Attributes go on the <form> element (...attributes), so class, id and novalidate work as usual.
Blocks
default
Yields one object, form here, whose properties stay current. A component inside the form can get the same object with useFormContext.
| Name | Type | Description |
|---|---|---|
errors | FormDataErrors<TForm> | Errors by field, from the last response or from Precognition. |
hasErrors | boolean | Whether errors has any field. |
processing | boolean | The request is in flight. |
progress | Progress | null | Upload progress (loaded, total, percentage) while files are sent. |
wasSuccessful | boolean | The last request succeeded. |
recentlySuccessful | boolean | The same, for form.recentlySuccessfulDuration (2000 ms by default). |
isDirty | boolean | The fields differ from their defaults: their values when the form was inserted, or at the last defaults(). |
submit | (submitter?: HTMLElement | null) => void | Submit, as if submitter (a button) had been clicked. |
reset | (...fields: string[]) => void | Put every field, or the named ones, back to their defaults. |
defaults | () => void | Take the current values as the defaults. |
clearErrors | (...fields: string[]) => void | Clear every error, or the named fields'. |
resetAndClearErrors | (...fields: string[]) => void | Both of the above. |
setError | (field, message) => void(errors) => void | Add errors by hand. |
cancel | () => void | Cancel the request in flight. |
getData | (submitter?: HTMLElement | null) => TForm | The fields as an object. Names such as address[city] and tags[] nest. |
getFormData | (submitter?: HTMLElement | null) => FormData | The fields as a DOM FormData. |
validating | boolean | A Precognition validation is in flight. |
validate | (field?, config?) => void | Validate a field against the server's rules, or the touched fields without one. An event passed by on as the last argument is ignored. |
touch | (...fields: string[]) => void | Mark fields as touched. |
touched | (field?) => boolean | Whether that field, or any, was touched. |
valid | (field) => boolean | The field passed its last validation. |
invalid | (field) => boolean | The field has an error. |
validator | () => Validator | null | The laravel-precognition validator behind it. |
Every function is bound, so it can be handed to on or fn as is. Mind what the event adds, though: submit and reset take their first argument as the submitter and field names, so use (fn form.submit null) and a <button type='reset'> rather than passing them the event.
useFormContext
function useFormContext<TForm extends object = Record<string, any>>(
element: Element | null | undefined,
): FormApi<TForm> | undefined;Returns the API of the <Form> around element (the same object the block yields), or undefined outside one. It's for components inside a form that weren't handed form. The form registers itself when its element is inserted, and the lookup isn't tracked, so call it when you need it (from an event handler, say) rather than in a getter a template renders.
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { useFormContext } from 'inertia-ember';
// <TextField @name='email' @label='Email' /> anywhere inside a <Form>
export default class TextField extends Component<{
Element: HTMLInputElement;
Args: { name: string; label: string };
}> {
validate = (event: Event) => {
useFormContext(event.target as Element)?.validate(this.args.name);
};
<template>
<label>
{{@label}}
<input name={{@name}} {{on 'change' this.validate}} ...attributes />
</label>
</template>
}createForm
function createForm<TForm extends object = Record<string, any>>(): ComponentLike<FormSignature<TForm>>;Returns <Form> itself, typed by its fields, as createForm<T>() does in the Vue and Svelte adapters. Glint then checks field names in the block's errors, reset, valid and the rest, and in @resetOnSuccess.
import { array } from '@ember/helper';
import { createForm } from 'inertia-ember';
const LoginForm = createForm<{ email: string; password: string }>();
<template>
<LoginForm @action='/login' @method='post' @resetOnError={{array 'password'}} as |form|>
<input type='email' name='email' />
{{form.errors.email}}
{{! form.errors.username would be a type error }}
<input type='password' name='password' />
<button>Log in</button>
</LoginForm>
</template>Examples
Submit and show errors
import { Form } from 'inertia-ember';
<template>
<Form @action='/posts' @method='post' @resetOnSuccess={{true}} @disableWhileProcessing={{true}} as |form|>
<input name='title' aria-invalid={{if form.errors.title 'true'}} />
{{#if form.errors.title}}<p>{{form.errors.title}}</p>{{/if}}
<textarea name='body'></textarea>
{{#if form.errors.body}}<p>{{form.errors.body}}</p>{{/if}}
<button disabled={{form.processing}}>Publish</button>
{{#if form.recentlySuccessful}}<span>Published.</span>{{/if}}
</Form>
</template>@onSuccess and @onError take functions: @onSuccess={{this.notify}}.
Track unsaved changes and reset
isDirty compares the fields with their values when the form appeared. A <button type='reset'> puts them back. For an edit form that stays on the page, @setDefaultsOnSuccess makes the saved values the new baseline.
<Form @action='/settings' @method='put' @setDefaultsOnSuccess={{true}} as |form|>
<input name='display_name' value={{@settings.displayName}} />
{{#if form.isDirty}}
<p>Unsaved changes</p>
<button type='reset'>Discard</button>
{{/if}}
<button disabled={{form.processing}}>Save</button>
</Form>Know which button was pressed, and transform the data
The clicked button's name and value are sent with the fields, as in a regular form. @transform changes the data on its way out.
import Component from '@glimmer/component';
import { Form, type FormDataConvertible } from 'inertia-ember';
export default class Editor extends Component {
clean = (data: Record<string, FormDataConvertible>) => ({ ...data, title: String(data.title ?? '').trim() });
<template>
<Form @action='/posts' @method='post' @transform={{this.clean}}>
<input name='title' />
<button name='status' value='draft'>Save draft</button>
<button name='status' value='published'>Publish</button>
</Form>
</template>
}Upload files and show progress
A file input's files go in the request, which Inertia sends as multipart/form-data.
<Form @action='/photos' @method='post' @resetOnSuccess={{true}} as |form|>
<input type='file' name='photos[]' multiple accept='image/*' />
{{#if form.progress}}
<progress value={{form.progress.percentage}} max='100'></progress>
{{/if}}
<button disabled={{form.processing}}>Upload</button>
<button type='button' disabled={{if form.processing false true}} {{on 'click' form.cancel}}>Cancel</button>
</Form>Validate fields with Precognition
Precognition is always available: validate sends the form to @action with the Precognition headers, and the server answers with that field's errors without running the action. The server has to support Precognition on that route. Errors show for fields that were validated or touched.
import { fn } from '@ember/helper';
import { on } from '@ember/modifier';
import { Form } from 'inertia-ember';
<template>
<Form @action='/users' @method='post' @validationTimeout={{500}} as |form|>
<input name='email' type='email' {{on 'change' (fn form.validate 'email')}} />
{{#if form.validating}}<span>Checking…</span>{{/if}}
{{#if (form.valid 'email')}}<span>✓</span>{{/if}}
{{#if (form.invalid 'email')}}<p>{{form.errors.email}}</p>{{/if}}
<button>Create</button>
</Form>
</template>form.validate() with no field validates every touched one, and a ValidationConfig such as (hash only=(array 'name' 'email')) picks the fields. See Precognition.
Filters that submit as they change
A GET form puts its fields in the query string, so the URL can be shared. (fn form.submit null) submits without passing the event as the submitter.
import { fn, hash } from '@ember/helper';
import { on } from '@ember/modifier';
import { Form } from 'inertia-ember';
<template>
<Form @action='/orders' @options={{hash preserveState=true preserveScroll=true replace=true}} as |form|>
<select name='status' {{on 'change' (fn form.submit null)}}>
<option value=''>Any status</option>
<option value='open'>Open</option>
<option value='shipped'>Shipped</option>
</select>
<input type='search' name='q' />
<button>Search</button>
</Form>
</template>A submit button with formtarget='_blank' opens a GET form's URL in a new tab instead.
Update the page before the server answers
@optimistic gets a copy of the page's props and the form's data, and returns the props to change. Inertia rolls the change back if the request fails.
import Component from '@glimmer/component';
import { Form, type PageProps, type PageSignature } from 'inertia-ember';
interface Comment {
id: number | null;
body: string;
}
export default class ShowPost extends Component<PageSignature<{ post: { id: number }; comments: Comment[] }>> {
addComment = (props: PageProps, data: { body?: string }) => ({
comments: [...(props.comments as Comment[]), { id: null, body: data.body ?? '' }],
});
<template>
{{#each @props.comments as |comment|}}<p>{{comment.body}}</p>{{/each}}
<Form
@action='/posts/{{@props.post.id}}/comments'
@method='post'
@optimistic={{this.addComment}}
@resetOnSuccess={{true}}
>
<textarea name='body'></textarea>
<button>Comment</button>
</Form>
</template>
}Notes
- Fields come from the DOM, so
<Form>works with any input, including ones rendered by other components, as long as they have aname. For state you read and change in code, useuseForm. - Precognition is always on, against
@actionand@method, as with the other adapters'<Form>. - The block yields a hash instead of slot props;
useFormContextstands in for the other adapters' form context.
Related: Forms, Precognition, useForm, <Link>.