useForm
Form state for an Inertia visit: tracked fields, errors and request state, and methods that send the fields to the server as an Inertia request. The server answers the way it answers any Inertia form: a redirect to the next page, or the same page with validation errors.
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { bind, useForm } from 'inertia-ember';
export default class SignUp extends Component {
form = useForm({ name: '', email: '' });
save = (event: SubmitEvent) => {
event.preventDefault();
this.form.post('/users');
};
<template>
<form {{on 'submit' this.save}}>
<input {{bind this.form 'name'}} />
<input type='email' {{bind this.form 'email'}} />
{{#if this.form.errors.email}}<p>{{this.form.errors.email}}</p>{{/if}}
<button disabled={{this.form.processing}}>Sign up</button>
</form>
</template>
}Each field is a tracked property of the form: form.email reads it, form.email = 'a@b.c' writes it, and templates update as it changes.
Signature
function useForm<TForm extends object = FormData>(data?: TForm | (() => TForm)): Form<TForm>;
// Remembers the fields and errors in history under `rememberKey`.
function useForm<TForm extends object = FormData>(
rememberKey: string | null | undefined,
data: TForm | (() => TForm),
): Form<TForm>;
// Turns on Precognition against this method and URL; `form.submit()` sends there.
function useForm<TForm extends object = FormData>(
method: Method | (() => Method),
url: string | (() => string),
data: TForm | (() => TForm),
): Form<TForm>;
function useForm<TForm extends object = FormData>(
action: UrlMethodPair | (() => UrlMethodPair),
data: TForm | (() => TForm),
): Form<TForm>;
// The form and its fields. Exported as the type `UseForm`.
type Form<TForm> = InertiaForm<TForm> & TForm;FormData here is the package's default shape, Record<string, FormDataConvertible> (exported as FormDataShape), not the DOM's FormData. InertiaForm, the class behind it, is exported too.
| Argument | Type | Description |
|---|---|---|
data | TForm | (() => TForm) | The fields and their defaults. A function is called again by reset(), so it can read current values; see defaults below. |
rememberKey | string | null | undefined | Keeps the fields and errors in history under this key, so they survive back and forward. A string first argument means this. |
method | Method | (() => Method) | With url: the Precognition endpoint, and where submit() sends. |
url | string | (() => string) | See method. |
action | UrlMethodPair | (() => UrlMethodPair) | A { url, method } pair instead of method and url, as route helpers generate. |
A field can't share its name with a property or method of the form (errors, data, get, delete, query, progress, reset, valid, and the rest of the tables below). Such a field logs an error and isn't reachable as form.<name>; rename it, or rename it in transform.
Properties
| Name | Type | Description |
|---|---|---|
form.<field> | TForm[field] | Each field, tracked. Assigning calls set. |
errors | FormDataErrors<TForm> | Errors by field, from the last response or from Precognition (a list per field for Precognition with withAllErrors()). The value type comes from errorValueType in your InertiaConfig. |
hasErrors | boolean | Whether errors has any field. |
isDirty | boolean | Whether the fields differ from the defaults (a deep comparison). |
processing | boolean | True from the request's start until it finishes. |
progress | Progress | null | Upload progress (loaded, total, percentage) while files are sent; null otherwise. |
wasSuccessful | boolean | The last request succeeded. Reset when the next one starts. |
recentlySuccessful | boolean | Like wasSuccessful, but turns false after form.recentlySuccessfulDuration (2000 ms by default). |
validating | boolean | A Precognition request is in flight. |
Methods
Methods that return this can be chained: useForm({ … }).transform(…).dontRemember('password').
| Name | Type | Description |
|---|---|---|
get, post, put, patch, delete, query | (url: string, options?: FormSubmitOptions) => void | Send the fields with that method. GET data goes in the query string. |
submit | (method, url, options?) => void(action: UrlMethodPair, options?) => void(options?) => void | The same, with the method as an argument. Without a method and URL it sends to the Precognition endpoint, and throws if there isn't one. |
cancel | () => void | Cancel the request in flight. |
data | () => TForm | The fields as a plain object (a deep copy). |
set | (field, value) => this(values: Partial<TForm>) => this | Set one field, or several. Dot paths reach nested values: set('address.city', 'Lima'), set('tags.0', 'new'). An unknown name adds a field. |
transform | (callback: (data: TForm) => object) => this | Change the data on its way out; the fields keep their values. |
defaults | () => this(field, value) => this(fields: Partial<TForm>) => this | Make the current data the defaults, or set some defaults. Throws when data was a function. |
reset | (...fields) => this | Back to the defaults: every field, or the ones named. With function data, calls it again and takes the result as the new defaults. |
setError | (field, message) => this(errors) => this | Add errors, keeping the others. |
setErrors | (errors) => this | setError with an object. |
clearErrors | (...fields) => this | Remove every error, or the named fields' errors. |
forgetError | (field | event) => this | Clear one field's error; takes an input event and reads its name. |
resetAndClearErrors | (...fields) => this | reset and clearErrors together. |
dontRemember | (...fields) => this | Leave these fields out of history when the form has a rememberKey. Each call replaces the list. |
optimistic | (callback: (props: PageProps) => Partial<PageProps> | void) => this | Apply callback to the page props for the next request, rolled back if it fails. See optimistic updates. |
Precognition adds withPrecognition, validate, touch, touched, valid, invalid, validator, setValidationTimeout, validateFiles, withoutFileValidation and withAllErrors; see Precognition below. invalid(field) works without Precognition too: it's true when errors has that field.
Submit options
FormSubmitOptions is Inertia's visit options without data: preserveScroll, preserveState, only, except, reset, replace, headers, errorBag, forceFormData, showProgress, async, viewTransition, the callbacks (onBefore, onStart, onProgress, onSuccess, onError, onCancel, onFinish, onHttpException, onNetworkError, onFlash, onCancelToken, …) and optimistic. Inertia core defines them: see manual visits in its docs.
Around your callbacks, the form keeps its own state:
- On start,
processingturns true;wasSuccessfulandrecentlySuccessfulturn false. - On success, errors are cleared,
wasSuccessfulandrecentlySuccessfulturn true, and after youronSuccessthe current data becomes the defaults, unlessonSuccesscalleddefaults()itself. - On error,
errorsis replaced by the response's errors. - On finish,
processingturns false andprogressback tonull.
Examples
Submit and show errors
The server answers a valid form with a redirect, and an invalid one with the page again and its errors, which fill form.errors. Callbacks such as onSuccess take the visit options.
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { bind, useForm } from 'inertia-ember';
export default class NewPost extends Component {
form = useForm({ title: '', body: '' });
save = (event: SubmitEvent) => {
event.preventDefault();
this.form.post('/posts', {
preserveScroll: true,
onSuccess: () => this.form.reset(),
});
};
<template>
<form {{on 'submit' this.save}}>
<input {{bind this.form 'title'}} aria-invalid={{if this.form.errors.title 'true'}} />
{{#if this.form.errors.title}}<p>{{this.form.errors.title}}</p>{{/if}}
<textarea {{bind this.form 'body'}}></textarea>
{{#if this.form.errors.body}}<p>{{this.form.errors.body}}</p>{{/if}}
<button disabled={{this.form.processing}}>Publish</button>
{{#if this.form.recentlySuccessful}}<span>Saved.</span>{{/if}}
</form>
</template>
}Track unsaved changes and reset
isDirty compares the fields with the defaults. A successful request makes the sent data the new defaults, so the form is clean again afterwards. Every method is bound, so {{on 'click' this.form.reset}} works as is.
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { bind, useForm } from 'inertia-ember';
export default class Profile extends Component<{ Args: { user: { name: string; bio: string } } }> {
form = useForm({ name: this.args.user.name, bio: this.args.user.bio });
save = (event: SubmitEvent) => {
event.preventDefault();
this.form.put('/profile');
};
discard = () => this.form.resetAndClearErrors();
<template>
<form {{on 'submit' this.save}}>
<input {{bind this.form 'name'}} />
<textarea {{bind this.form 'bio'}}></textarea>
{{#if this.form.isDirty}}
<p>Unsaved changes</p>
<button type='button' {{on 'click' this.discard}}>Discard</button>
{{/if}}
<button disabled={{this.form.processing}}>Save</button>
</form>
</template>
}form.reset('bio') resets one field, form.defaults() takes the current values as the new defaults, and form.defaults('bio', '') changes one default.
Change the data before it's sent
transform runs on every submit. The fields keep what the user typed.
form = useForm({ email: '', password: '', remember: false }).transform((data) => ({
...data,
email: data.email.trim().toLowerCase(),
}));Upload files and show progress
A File in the fields sends the request as multipart/form-data. {{bind}} on a file input sets the field to a File (or a list with multiple). progress follows the upload.
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { bind, useForm } from 'inertia-ember';
export default class Avatar extends Component {
form = useForm<{ avatar: File | null }>({ avatar: null });
upload = (event: SubmitEvent) => {
event.preventDefault();
this.form.post('/profile/avatar', { onSuccess: () => this.form.reset() });
};
<template>
<form {{on 'submit' this.upload}}>
<input type='file' accept='image/*' {{bind this.form 'avatar'}} />
{{#if this.form.progress}}
<progress value={{this.form.progress.percentage}} max='100'></progress>
{{/if}}
{{#if this.form.errors.avatar}}<p>{{this.form.errors.avatar}}</p>{{/if}}
<button disabled={{this.form.processing}}>Upload</button>
</form>
</template>
}Resetting the field to null clears the file input. Inertia core decides how files are encoded; see file uploads in its docs.
Keep the input across back and forward
With a key first, the fields and errors are saved in history as they change and restored when the user comes back to the page. Leave secrets out with dontRemember.
form = useForm(`Posts/Edit:${this.args.post.id}`, {
title: this.args.post.title,
body: this.args.post.body,
});
login = useForm('Login', { email: '', password: '' }).dontRemember('password');The key has to be unique among the forms in history, so include the record's id when there's one.
Update the page before the server answers
optimistic changes the page's props right away, and Inertia rolls them back if the request fails. The callback gets a copy of the current props and the data being sent, and returns the props to change. Pass it to optimistic() before sending, or as the optimistic option.
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { type PageSignature, useForm } from 'inertia-ember';
interface Post {
id: number;
likes: number;
}
export default class ShowPost extends Component<PageSignature<{ post: Post }>> {
form = useForm({});
like = () => {
this.form
.optimistic((props) => {
const post = props.post as Post;
return { post: { ...post, likes: post.likes + 1 } };
})
.post(`/posts/${this.args.props.post.id}/like`, { preserveScroll: true });
};
<template>
<button type='button' {{on 'click' this.like}}>♥ {{@props.post.likes}}</button>
</template>
}The rollback and the merging of the server's answer are Inertia core's; see its docs on optimistic updates at inertiajs.com.
Precognition
With a method and URL, the form can validate against the server's rules before it's sent. The server has to support Precognition on that route: it validates the request and answers without running the action. The protocol and the validator come from Inertia core and laravel-precognition.
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { bind, useForm } from 'inertia-ember';
export default class NewUser extends Component {
form = useForm('post', '/users', { name: '', email: '' }).setValidationTimeout(500);
save = (event: SubmitEvent) => {
event.preventDefault();
this.form.submit(); // post /users
};
<template>
<form {{on 'submit' this.save}}>
<input type='email' {{bind this.form 'email' validate=true}} />
{{#if this.form.validating}}<span>Checking…</span>{{/if}}
{{#if (this.form.valid 'email')}}<span>✓</span>{{/if}}
{{#if (this.form.invalid 'email')}}<p>{{this.form.errors.email}}</p>{{/if}}
<button disabled={{this.form.processing}}>Create</button>
</form>
</template>
}validate=true on {{bind}} validates the field on change (when a text input loses focus); see {{bind}}. Without {{bind}}, call validate yourself: {{on 'blur' (fn this.form.validate 'email')}}. The event that fn passes along is ignored.
| Name | Type | Description |
|---|---|---|
withPrecognition | (method, url) => this(action: UrlMethodPair) => this | Turn Precognition on for a form made without a method and URL. Each may be a function. |
validate | (field?, config?) => this | Validate one field (a name, or an input event whose target has a name), or the touched fields without one. Throws without Precognition. |
touch | (field | fields[], ...fields) => this | Mark fields as touched, so validate() includes them. |
touched | (field?) => boolean | Whether that field, or any field, was touched. |
valid | (field) => boolean | The field passed its last validation. |
invalid | (field) => boolean | The field has an error. |
validating | boolean | A validation request is in flight. |
setValidationTimeout | (ms: number) => this | The debounce between validations; 1500 ms by default. Throws without Precognition. |
validateFiles, withoutFileValidation | () => this | Send files in validation requests, or don't. Files aren't sent unless you call validateFiles(). |
withAllErrors | () => this | Keep every message per field (errors.email becomes a list) instead of the first. Also set by the form.withAllErrors default. |
validator | () => Validator | null | The underlying laravel-precognition validator, or null without Precognition. |
The optional config of validate is laravel-precognition's ValidationConfig: only (fields to validate), headers, and callbacks such as onSuccess, onValidationError, onBefore and onFinish. It can also be the first argument: form.validate({ only: ['email', 'name'] }).
Validate a step before moving on
next = () => {
this.form.validate({
only: ['name', 'email'],
onSuccess: () => (this.step = 2),
});
};Errors only for touched fields
Precognition shows errors for the fields that were validated or touched, so the user isn't greeted by errors on fields they haven't reached. touch('email') marks a field by hand, and validate() with no field sends every touched one.
A validation still waiting out its debounce is dropped when the form is sent, so it can't arrive after the submit.
Notes
- Fields are properties, as in the Vue adapter:
form.title, notform.data.title.setstands in for React'ssetData, and{{bind}}forv-model. - Every method is bound to the form, so a template can call or pass any of them directly:
{{on 'click' this.form.reset}},(this.form.valid 'email'). As handlers,reset,clearErrorsandresetAndClearErrorsignore the event (so every field resets), and{{on 'submit' this.form.submit}}stops the browser's own submit and sends through Inertia. optimisticgets the props and the form's data,(props, data), as<Form @optimistic>does.- Defaults for every form, such as
recentlySuccessfulDurationandwithAllErrors, go increateInertiaApp'sdefaults: { form: { … } }.
Related: Forms, Precognition, {{bind}}, <Form>, useHttp.