Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions docs/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@
"to": "framework/svelte/quick-start"
}
]
},
{
"label": "ember",
"children": [
{
"label": "Quick Start",
"to": "framework/ember/quick-start"
}
]
}
]
},
Expand Down Expand Up @@ -309,6 +318,39 @@
"to": "framework/svelte/guides/form-composition"
}
]
},
{
"label": "ember",
"children": [
{
"label": "Basic Concepts",
"to": "framework/ember/guides/basic-concepts"
},
{
"label": "Form Validation",
"to": "framework/ember/guides/validation"
},
{
"label": "Dynamic Validation",
"to": "framework/ember/guides/dynamic-validation"
},
{
"label": "Async Initial Values",
"to": "framework/ember/guides/async-initial-values"
},
{
"label": "Arrays",
"to": "framework/ember/guides/arrays"
},
{
"label": "Linked Fields",
"to": "framework/ember/guides/linked-fields"
},
{
"label": "Form Composition",
"to": "framework/ember/guides/form-composition"
}
]
}
]
},
Expand Down
121 changes: 121 additions & 0 deletions docs/framework/ember/guides/arrays.md
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|}}
Copy link
Copy Markdown

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?

{{!-- ... --}}
{{/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}}`.
108 changes: 108 additions & 0 deletions docs/framework/ember/guides/async-initial-values.md
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.
Loading