Forms
There are two ways to send a form, as in the other adapters: useForm, which keeps the fields in tracked state, and <Form>, which keeps no state and reads the fields from the DOM.
useForm
useForm gives you tracked fields, errors and state. The {{bind}} modifier connects an input to a field: text, number, checkbox (a boolean, or a list of values when the field holds an array), radio, select, multi-select and file.
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { bind, useForm } from 'inertia-ember';
export default class Edit extends Component {
form = useForm(`Posts/Edit:${this.args.props.post.id}`, { title: this.args.props.post.title });
save = (event: SubmitEvent) => {
event.preventDefault();
this.form.put(`/posts/${this.args.props.post.id}`, { preserveScroll: true });
};
<template>
<form {{on 'submit' this.save}}>
<input {{bind this.form 'title'}} />
{{#if this.form.errors.title}}<p>{{this.form.errors.title}}</p>{{/if}}
<button disabled={{this.form.processing}}>Save</button>
{{if this.form.isDirty 'Unsaved changes'}}
</form>
</template>
}Passing a key first (Posts/Edit:1 above) remembers the form in history, so it survives the back button.
| Member | What it does |
|---|---|
form.title, data(), set(path, value) | The fields. set takes dot paths: set('address.city'). |
errors, hasErrors, setError, clearErrors | Validation errors from the server. |
processing, progress, wasSuccessful, recentlySuccessful | Where the request is. |
isDirty, defaults, reset, resetAndClearErrors | Changes since the defaults. |
get/post/put/patch/delete, submit, cancel | Sending it. |
transform, optimistic, dontRemember | Changing the data, optimistic updates, history. |
The demo's comment form, on each idea, is a useForm. Try it ↗
<Form>
<Form> keeps no state of its own. It reads the fields from the DOM by name, and yields the form's state:
<Form @action='/posts' @method='post' @resetOnSuccess={{true}} as |form|>
<input name='title' />
{{#if form.errors.title}}<p>{{form.errors.title}}</p>{{/if}}
<button disabled={{form.processing}}>Publish</button>
</Form>It yields errors, hasErrors, processing, progress, wasSuccessful, recentlySuccessful, isDirty, submit, reset, defaults, clearErrors, resetAndClearErrors, setError, cancel, getData and getFormData, plus Precognition against its own action.
It also takes @transform, @errorBag, @resetOnError, @setDefaultsOnSuccess, @disableWhileProcessing, @cancelOnUnmount, @invalidateCacheTags, @optimistic, @validationTimeout (1500 ms), @validateFiles and @withAllErrors.
A component inside it gets the same API with useFormContext(element). createForm<T>() returns a <Form> whose block knows its field names, for TypeScript and for code that follows the Vue and Svelte adapters.
The demo's New idea page is a <Form>. See its source, or