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
112 changes: 112 additions & 0 deletions docs/framework/ember/guides/arrays.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
---
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 { createForm } from '@tanstack/ember-form';

const PeopleForm = createForm({
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's name this as form, and follow the standard tanstack docs for how to use a form object

We'll need to show examples of how to use both in a template-only component, as well as a class-based component

defaultValues: {
people: [],
},
});

<template>
<PeopleForm as |Form|>
<Form.Field @name="people" @mode="array" as |field|>
{{#each field.state.value as |person|}}
{{!-- ... --}}
{{/each}}
</Form.Field>
</PeopleForm>
</template>
```

This will regenerate the list every time you run `pushValue` on `field`:

```gjs
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
const handleInput = (field, event) => field.handleChange(event.target.value);
const nameAt = (i) => `people[${i}].name`;

{{!-- inside a template --}}
<Form.Field @name={{nameAt i}} as |subField|>
<input
value={{subField.state.value}}
{{on "input" (fn handleInput subField)}}
/>
</Form.Field>
```

## Full Example

```gjs
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 });

const onSubmitFor = (form) => (event) => {
event.preventDefault();
event.stopPropagation();
form.handleSubmit();
};

const handleSubmit = ({ value }) => alert(JSON.stringify(value));

const PeopleForm = createForm({
defaultValues: {
people: [] as Array<{ age: number; name: string }>,
},
});

<template>
<PeopleForm @onSubmit={{handleSubmit}} as |Form|>
<form id="form" {{on "submit" (onSubmitFor Form)}}>
<Form.Field @name="people" as |field|>
<div>
{{#each field.state.value as |person i|}}
<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>
</Form.Field>
{{/each}}

<button {{on "click" (fn addPerson field)}} type="button">
Add person
</button>
</div>
</Form.Field>

<button type="submit">Submit</button>
</form>
</PeopleForm>
</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}}`.
133 changes: 133 additions & 0 deletions docs/framework/ember/guides/async-initial-values.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
---
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 the invocation as `@defaultValues`.

Because `createForm` is called at module scope, the component it returns is constructed every time it's invoked in a template. The simplest pattern is to render the form invocation inside an `{{#if}}` that gates on the loading state and pass the resolved data as `@defaultValues`. The arg-level `@defaultValues` is merged with anything baked into `createForm`, so per-instance overrides are straightforward.

```gjs
// person-form.gts
import { createForm } from '@tanstack/ember-form';

const handleInput = (field, event) => field.handleChange(event.target.value);

const onSubmitFor = (form) => (event) => {
event.preventDefault();
event.stopPropagation();
form.handleSubmit();
};

const handleSubmit = async ({ value }) => {
// Do something with form data
console.log(value);
};

export const PersonForm = createForm({
// Sensible fallbacks; the caller can override via @defaultValues
defaultValues: {
firstName: '',
lastName: '',
},
});

<template>
<PersonForm
@defaultValues={{@initial}}
@onSubmit={{handleSubmit}}
as |Form|
>
<form {{on "submit" (onSubmitFor Form)}}>
<Form.Field @name="firstName" as |field|>
<input
name={{field.name}}
value={{field.state.value}}
{{on "blur" field.handleBlur}}
{{on "input" (fn handleInput field)}}
/>
</Form.Field>
<Form.Field @name="lastName" as |field|>
<input
name={{field.name}}
value={{field.state.value}}
{{on "blur" field.handleBlur}}
{{on "input" (fn handleInput field)}}
/>
</Form.Field>
<button type="submit">Submit</button>
</form>
</PersonForm>
</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 @defaultValues={{this.request.value}} />
{{/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 invoked once `request.value` is defined, the form is constructed with 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 invoke the form component until the data is ready.

## Wrapping the form in a component that consumes the resolved data

If you'd rather encapsulate the form invocation alongside other component-local state, write a Glimmer component that takes the resolved data as an arg and renders the form internally:

```gjs
// person-form-loader.gts
import Component from '@glimmer/component';
import { trackedFunction } from 'reactiveweb/function';
import { PersonForm } from './person-form.gts';

export default class PersonFormLoader 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 @defaultValues={{this.request.value}} />
{{/if}}
</template>
}
```

## Updating defaults after the form is mounted

If you'd rather invoke the form immediately and patch values in once data arrives, you can call `form.update({ defaultValues: ... })` (or `form.reset(values)`) from inside a child component that receives the form as `@form` (e.g. via a `<Subscribe>` selector or a `{{didUpdate}}` modifier triggered 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