Skip to content

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.

gts
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 ​

ts
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.

ArgumentTypeDescription
dataTForm | (() => TForm)The fields and their defaults. A function is called again by reset(), so it can read current values; see defaults below.
rememberKeystring | null | undefinedKeeps the fields and errors in history under this key, so they survive back and forward. A string first argument means this.
methodMethod | (() => Method)With url: the Precognition endpoint, and where submit() sends.
urlstring | (() => string)See method.
actionUrlMethodPair | (() => 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 ​

NameTypeDescription
form.<field>TForm[field]Each field, tracked. Assigning calls set.
errorsFormDataErrors<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.
hasErrorsbooleanWhether errors has any field.
isDirtybooleanWhether the fields differ from the defaults (a deep comparison).
processingbooleanTrue from the request's start until it finishes.
progressProgress | nullUpload progress (loaded, total, percentage) while files are sent; null otherwise.
wasSuccessfulbooleanThe last request succeeded. Reset when the next one starts.
recentlySuccessfulbooleanLike wasSuccessful, but turns false after form.recentlySuccessfulDuration (2000 ms by default).
validatingbooleanA Precognition request is in flight.

Methods ​

Methods that return this can be chained: useForm({ … }).transform(…).dontRemember('password').

NameTypeDescription
get, post, put, patch, delete, query(url: string, options?: FormSubmitOptions) => voidSend 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() => voidCancel the request in flight.
data() => TFormThe 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) => thisChange 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) => thisBack 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) => thissetError with an object.
clearErrors(...fields) => thisRemove every error, or the named fields' errors.
forgetError(field | event) => thisClear one field's error; takes an input event and reads its name.
resetAndClearErrors(...fields) => thisreset and clearErrors together.
dontRemember(...fields) => thisLeave these fields out of history when the form has a rememberKey. Each call replaces the list.
optimistic(callback: (props: PageProps) => Partial<PageProps> | void) => thisApply 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, processing turns true; wasSuccessful and recentlySuccessful turn false.
  • On success, errors are cleared, wasSuccessful and recentlySuccessful turn true, and after your onSuccess the current data becomes the defaults, unless onSuccess called defaults() itself.
  • On error, errors is replaced by the response's errors.
  • On finish, processing turns false and progress back to null.

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.

gts
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.

gts
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.

ts
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.

gts
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.

ts
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.

gts
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.

gts
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.

NameTypeDescription
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?) => thisValidate 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) => thisMark fields as touched, so validate() includes them.
touched(field?) => booleanWhether that field, or any field, was touched.
valid(field) => booleanThe field passed its last validation.
invalid(field) => booleanThe field has an error.
validatingbooleanA validation request is in flight.
setValidationTimeout(ms: number) => thisThe debounce between validations; 1500 ms by default. Throws without Precognition.
validateFiles, withoutFileValidation() => thisSend files in validation requests, or don't. Files aren't sent unless you call validateFiles().
withAllErrors() => thisKeep every message per field (errors.email becomes a list) instead of the first. Also set by the form.withAllErrors default.
validator() => Validator | nullThe 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 ​

ts
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, not form.data.title. set stands in for React's setData, and {{bind}} for v-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, clearErrors and resetAndClearErrors ignore the event (so every field resets), and {{on 'submit' this.form.submit}} stops the browser's own submit and sends through Inertia.
  • optimistic gets the props and the form's data, (props, data), as <Form @optimistic> does.
  • Defaults for every form, such as recentlySuccessfulDuration and withAllErrors, go in createInertiaApp's defaults: { form: { … } }.

Related: Forms, Precognition, {{bind}}, <Form>, useHttp.

Released under the MIT License.