-
-
Notifications
You must be signed in to change notification settings - Fork 627
feat(ember-form): add Ember adapter (@tanstack/ember-form) #2156
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
NullVoxPopuli-ai-agent
wants to merge
3
commits into
TanStack:main
Choose a base branch
from
NullVoxPopuli-ai-agent:ember-form-adapter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+8,802
−410
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| --- | ||
| id: arrays | ||
| title: Arrays | ||
| --- | ||
|
|
||
| TanStack Form supports arrays as values in a form, including sub-object values inside of an array. | ||
|
|
||
| ## Basic Usage | ||
|
|
||
| To use an array, you can iterate over `field.state.value` with [`{{#each}}`](https://api.emberjs.com/ember/release/classes/Ember.Templates.helpers/methods/each): | ||
|
|
||
| ```gjs | ||
| import Component from '@glimmer/component'; | ||
| import { createForm } from '@tanstack/ember-form'; | ||
|
|
||
| export default class PeopleForm extends Component { | ||
| form = createForm(this, { | ||
| defaultValues: { | ||
| people: [], | ||
| }, | ||
| }); | ||
|
|
||
| <template> | ||
| <this.form.Field @name="people" @mode="array" as |field|> | ||
| {{#each field.state.value as |person i|}} | ||
| {{!-- ... --}} | ||
| {{/each}} | ||
| </this.form.Field> | ||
| </template> | ||
| } | ||
| ``` | ||
|
|
||
| This will regenerate the list every time you run `pushValue` on `field`: | ||
|
|
||
| ```gjs | ||
| import { fn } from '@ember/helper'; | ||
| import { on } from '@ember/modifier'; | ||
|
|
||
| const addPerson = (field) => field.pushValue({ name: '', age: 0 }); | ||
|
|
||
| {{!-- inside a template --}} | ||
| <button {{on "click" (fn addPerson field)}} type="button"> | ||
| Add person | ||
| </button> | ||
| ``` | ||
|
|
||
| Finally, you can use a subfield like so: | ||
|
|
||
| ```gjs | ||
| import { fn } from '@ember/helper'; | ||
| import { on } from '@ember/modifier'; | ||
|
|
||
| const handleInput = (field, event) => field.handleChange(event.target.value); | ||
| const nameAt = (i) => `people[${i}].name`; | ||
|
|
||
| {{!-- inside a template --}} | ||
| <this.form.Field @name={{nameAt i}} as |subField|> | ||
| <input | ||
| value={{subField.state.value}} | ||
| {{on "input" (fn handleInput subField)}} | ||
| /> | ||
| </this.form.Field> | ||
| ``` | ||
|
|
||
| ## Full Example | ||
|
|
||
| ```gjs | ||
| import Component from '@glimmer/component'; | ||
| import { fn } from '@ember/helper'; | ||
| import { on } from '@ember/modifier'; | ||
| import { createForm } from '@tanstack/ember-form'; | ||
|
|
||
| const handleInput = (field, event) => field.handleChange(event.target.value); | ||
| const nameAt = (i) => `people[${i}].name`; | ||
| const addPerson = (field) => field.pushValue({ name: '', age: 0 }); | ||
|
|
||
| export default class PeopleForm extends Component { | ||
| form = createForm(this, { | ||
| defaultValues: { | ||
| people: [] as Array<{ age: number; name: string }>, | ||
| }, | ||
| onSubmit: ({ value }) => alert(JSON.stringify(value)), | ||
| }); | ||
|
|
||
| submit = (event) => { | ||
| event.preventDefault(); | ||
| event.stopPropagation(); | ||
| this.form.handleSubmit(); | ||
| }; | ||
|
|
||
| <template> | ||
| <form id="form" {{on "submit" this.submit}}> | ||
| <this.form.Field @name="people" as |field|> | ||
| <div> | ||
| {{#each field.state.value as |person i|}} | ||
| <this.form.Field @name={{nameAt i}} as |subField|> | ||
| <div> | ||
| <label> | ||
| <div>Name for person {{i}}</div> | ||
| <input | ||
| value={{person.name}} | ||
| {{on "input" (fn handleInput subField)}} | ||
| /> | ||
| </label> | ||
| </div> | ||
| </this.form.Field> | ||
| {{/each}} | ||
|
|
||
| <button {{on "click" (fn addPerson field)}} type="button"> | ||
| Add person | ||
| </button> | ||
| </div> | ||
| </this.form.Field> | ||
|
|
||
| <button type="submit">Submit</button> | ||
| </form> | ||
| </template> | ||
| } | ||
| ``` | ||
|
|
||
| > Note: in strict-mode templates you can't put complex expressions like `` `people[${i}].name` `` directly into an attribute or argument value. The `nameAt` helper above is a small module-level function that does the templating in JavaScript and is then invoked as `{{nameAt i}}`. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| --- | ||
| id: async-initial-values | ||
| title: Async Initial Values | ||
| --- | ||
|
|
||
| Let's say that you want to fetch some data from an API and use it as the initial value of a form. | ||
|
|
||
| While this problem sounds simple on the surface, there are hidden complexities you might not have thought of thus far. | ||
|
|
||
| For example, you might want to show a loading spinner while the data is being fetched, or you might want to handle errors gracefully. Likewise, you could also find yourself looking for a way to cache the data so that you don't have to fetch it every time the form is rendered. | ||
|
|
||
| While we could implement many of these features from scratch, it would end up looking a lot like another project we maintain: [TanStack Query](https://tanstack.com/query). | ||
|
|
||
| As such, this guide shows you how you can mix-n-match TanStack Form with a data-loading utility (such as [`ember-resources`](https://github.com/NullVoxPopuli/ember-resources), [warp-drive](https://github.com/emberjs/data), or your own routing layer) to achieve the desired behavior. | ||
|
|
||
| ## Basic Usage | ||
|
|
||
| The general shape of the solution is: | ||
|
|
||
| 1. Load the data outside of the form (in a route, a resource, or a parent component). | ||
| 2. Render the form only once the data is available, passing the resolved values into `defaultValues`. | ||
|
|
||
| Because `createForm` runs at component construction time, the simplest pattern is to render the form-bearing component inside an `{{#if}}` that gates on the loading state. That way, by the time `createForm` runs, `defaultValues` is already populated. | ||
|
|
||
| ```gjs | ||
| // person-form.gts | ||
| import Component from '@glimmer/component'; | ||
| import { fn } from '@ember/helper'; | ||
| import { on } from '@ember/modifier'; | ||
| import { createForm } from '@tanstack/ember-form'; | ||
|
|
||
| const handleInput = (field, event) => field.handleChange(event.target.value); | ||
|
|
||
| export default class PersonForm extends Component { | ||
| // Args: { firstName: string; lastName: string } | ||
| form = createForm(this, { | ||
| defaultValues: { | ||
| firstName: this.args.firstName ?? '', | ||
| lastName: this.args.lastName ?? '', | ||
| }, | ||
| onSubmit: async ({ value }) => { | ||
| // Do something with form data | ||
| console.log(value); | ||
| }, | ||
| }); | ||
|
|
||
| submit = (event) => { | ||
| event.preventDefault(); | ||
| event.stopPropagation(); | ||
| this.form.handleSubmit(); | ||
| }; | ||
|
|
||
| <template> | ||
| <form {{on "submit" this.submit}}> | ||
| <this.form.Field @name="firstName" as |field|> | ||
| <input | ||
| name={{field.name}} | ||
| value={{field.state.value}} | ||
| {{on "blur" field.handleBlur}} | ||
| {{on "input" (fn handleInput field)}} | ||
| /> | ||
| </this.form.Field> | ||
| <this.form.Field @name="lastName" as |field|> | ||
| <input | ||
| name={{field.name}} | ||
| value={{field.state.value}} | ||
| {{on "blur" field.handleBlur}} | ||
| {{on "input" (fn handleInput field)}} | ||
| /> | ||
| </this.form.Field> | ||
| <button type="submit">Submit</button> | ||
| </form> | ||
| </template> | ||
| } | ||
| ``` | ||
|
|
||
| ```gjs | ||
| // page.gts | ||
| import Component from '@glimmer/component'; | ||
| import { trackedFunction } from 'reactiveweb/function'; | ||
| import PersonForm from './person-form.gts'; | ||
|
|
||
| export default class PersonPage extends Component { | ||
| request = trackedFunction(this, async () => { | ||
| await new Promise((resolve) => setTimeout(resolve, 1000)); | ||
| return { firstName: 'FirstName', lastName: 'LastName' }; | ||
| }); | ||
|
|
||
| <template> | ||
| {{#if this.request.isPending}} | ||
| <p>Loading...</p> | ||
| {{else if this.request.value}} | ||
| <PersonForm | ||
| @firstName={{this.request.value.firstName}} | ||
| @lastName={{this.request.value.lastName}} | ||
| /> | ||
| {{/if}} | ||
| </template> | ||
| } | ||
| ``` | ||
|
|
||
| This will show a loading spinner until the data is fetched, and then it will render the form with the fetched data as the initial values. Because `<PersonForm>` is only constructed once `request.value` is defined, `createForm` sees the resolved values on mount. | ||
|
|
||
| > The example above uses [`reactiveweb`](https://github.com/universal-ember/reactiveweb)'s `trackedFunction`, but the pattern is the same with any data-loading primitive — Ember's route model, ember-resources, `Resource` from `@warp-drive/*`, or even a hand-rolled async getter. The key invariant is: don't construct the form until the data is ready. | ||
|
|
||
| ## Updating defaults after the form is mounted | ||
|
|
||
| If you'd rather render the form immediately and patch values in once data arrives, you can call `form.update({ defaultValues: ... })` (or `form.reset(values)`) from a `@cached` getter or an effect when the loaded data changes. Be aware that updating `defaultValues` after fields have been touched will not overwrite user input — that is by design. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why specify
i? do we expect users to care about the index?