* feat: initial work on FormGroupApi in core * chore: initial (and wrong) per-form-group-validation This is wrong because instead of keeping the state inside of `FormGroupApi` itself, we need to follow the same pattern of `FieldApi` and keep the state in `FormApi` and reference that state in a derived way. * chore: create a common FieldLikeAPI to adopt in form groups shortly * chore: implement FieldLike API on FormGroup * chore: revert changes to FormApi validation logic * chore: fix type issues with validation kind * chore: minor fixes * Revert "chore: revert changes to FormApi validation logic" This reverts commit756ddf8402. * chore: filter fields to validate in formgroup * chore: improve store * chore: fix tests * chore: fix another test * chore: add submitmeta test * ci: apply automated fixes and generate docs * chore: add FormLike methods to FormGroup * chore: add type tests * chore: fix build * chore: fix type tests * ci: apply automated fixes and generate docs * chore: export two missing items * chore: add new interop FormGroupOptions type * chore: initial implement of useFormGroup in React * ci: apply automated fixes and generate docs * chore: add formGroup to useForm * chore: add initial React implementation tests * ci: apply automated fixes and generate docs * chore: add type tests for React adapter * ci: apply automated fixes and generate docs * chore: fix eslint * ci: apply automated fixes and generate docs * chore: add multi-step wizard * ci: apply automated fixes and generate docs * fix: handle resubmissions * fix: validate on resubmit * feat: add better onDynamic handling to FormGroupApi * chore: first attempt to fix onDynamic change handling on groups * chore: attempt 2 * chore: attempt 3 * chore: attempt 4 * Revert "chore: attempt 4" This reverts commit7546f08b94. * chore: finalize fixing form errors * chore: fix eslint * chore: regenerate lockfile * ci: apply automated fixes and generate docs * docs: update the wizard example * ci: apply automated fixes and generate docs * chore: initial work on Vue FormGroup API * ci: apply automated fixes and generate docs * chore: revert useContext changes * feat: add preact form group * chore: fix tests and export names * chore: add Preact wizard demo * feat: add FormGroup support for Solid adapter * chore: add formgroup tests for Solid * chore: add type tests for Solid * ci: apply automated fixes and generate docs * chore: add Solid group example * ci: apply automated fixes and generate docs * chore: fix test * feat: add FormGroup impl to Svelte * ci: apply automated fixes and generate docs * chore: add formGroup tests for Svelte * ci: apply automated fixes and generate docs * chore: add Svelte example * chore: fix sherif * feat: add Lit FormGroup API * chore: add Lit FormGroup tests * chore: refactor Lit tests * ci: apply automated fixes and generate docs * feat: implement FormGroup in Angular * chore: add FormGroup Angular spec * ci: apply automated fixes and generate docs * feat: add withForm feature to Angular * chore: update Angular large-form example to use new `withForm` API * docs: add docs to Angular withForm example * chore: add changeset * chore: fix knip * chore: initial multi-step-wizard Angular example * chore: update the multi-step-wizard to use new API * chore: add multi-step-wizard example to Lit * ci: apply automated fixes and generate docs * chore: add Vue example * chore: fix CI * chore: update to use Testing Library * chore: make tests more Testing Library-y * fix: isSubmitting now works with FormGroup Thank you @gaganref! * chore: fix Lit warning * ci: apply automated fixes and generate docs * chore: add currently failing tests * fix: handle validation better in form groups * chore: add test for duped group schema * chore: update `form` error field to `group` * chore: fix CI * ci: apply automated fixes and generate docs * chore: add test for isGroupValid and isFieldsValid * ci: apply automated fixes and generate docs * chore: refactor FormGroup to core * chore: refactor Lit Form to use Lit Store properly * chore: fix eslint * ci: apply automated fixes and generate docs * chore: remove temp changeset * docs: initial docs for React adapter * docs: add multi-step-wizard examples to docs site * docs: add form group state docs for React * docs: mirror React docs to Preact * docs: add Solid docs * docs: add Vue docs * ci: apply automated fixes and generate docs * docs: add groups docs for Svelte * docs: add groups docs for Lit * docs: add groups docs for Angular * fix: handle issue with field group names * ci: apply automated fixes and generate docs * chore: fix CI * chore: remove onXListenTo APIs * chore: add onMount errors to groups * chore: add onChange listeners to form * chore: handle group validation async cleanup, onmount listener, et al * chore: fix Group change listeners * chore: add changeset --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
7.8 KiB
| id | title |
|---|---|
| form-groups | Form Groups |
When building a multi-stage form that has many stages, like so:
It's common for each step to have its own form. However, this complicates the form submission and validation process by requiring you to add complex logic.
Luckily, TanStack Form provides a way to build out sub-forms that make this kind of development trivial to implement: [tanstackFormGroup].
Usage
To use a form group in TanStack Form, you'll use injectForm to create a form variable, then reference it with the tanstackFormGroup directive like you would with tanstackField:
import { Component } from '@angular/core'
import { TanStackFormGroup, injectForm } from '@tanstack/angular-form'
@Component({
selector: 'app-root',
standalone: true,
imports: [TanStackFormGroup],
template: `
<ng-container [tanstackFormGroup]="form" name="step1" #group="formGroup">
<!-- `group.api` here has all of the form-like methods you'd expect like `deleteField` or `insertFieldValue` -->
<!-- ... -->
</ng-container>
`,
})
export class AppComponent {
form = injectForm({
defaultValues: {
step1: {
name: '',
},
step2: {
age: 0,
},
},
})
}
This becomes much more useful when paired with external state to conditionally render a form group:
import { Component, signal } from '@angular/core'
import {
TanStackField,
TanStackFormGroup,
injectForm,
} from '@tanstack/angular-form'
@Component({
selector: 'app-root',
standalone: true,
imports: [TanStackField, TanStackFormGroup],
template: `
@if (step() === 0) {
<ng-container
[tanstackFormGroup]="form"
name="step1"
[onGroupSubmit]="onStep1Submit"
[onGroupSubmitInvalid]="onStep1SubmitInvalid"
[onSubmitMeta]="submitMeta"
#group="formGroup"
>
<form
(submit)="
$event.preventDefault();
$event.stopPropagation();
group.api.handleSubmit()
"
>
<ng-container [tanstackField]="form" name="step1.name" #name="field">
<!-- ... -->
</ng-container>
</form>
</ng-container>
}
@if (step() === 1) {
<ng-container
[tanstackFormGroup]="form"
name="step2"
[onGroupSubmit]="onStep2Submit"
#group="formGroup"
>
<form
(submit)="
$event.preventDefault();
$event.stopPropagation();
group.api.handleSubmit()
"
>
<ng-container [tanstackField]="form" name="step2.age" #age="field">
<!-- ... -->
</ng-container>
</form>
</ng-container>
}
`,
})
export class AppComponent {
step = signal(0)
submitMeta = {} as SomeType
form = injectForm({
defaultValues: {
step1: {
name: '',
},
step2: {
age: 0,
},
},
})
onStep1Submit = () => {
// We can move the step forward when validation passes
this.step.update((step) => step + 1)
}
onStep1SubmitInvalid = () => {
// Or handle invalid submissions, just like a top-level form
}
onStep2Submit = () => {
// Then, use `form.handleSubmit()` to submit the entire form
this.form.handleSubmit()
}
}
When you split each step into its own component, pass the parent form down with tanstack-with-form and read it in the child with injectWithForm. The child can then use [tanstackFormGroup]="withForm.form" and [tanstackField]="withForm.form" against the same parent form instance.
Form Group Validation
Form groups have a distinct validation procedure that we think makes sense for sub-forms:
- Form groups can have their own validation:
@Component({
selector: 'app-root',
standalone: true,
imports: [TanStackFormGroup],
template: `
<ng-container
[tanstackFormGroup]="form"
name="step1"
[validators]="{ onChange: groupValidator }"
#group="formGroup"
>
<!-- group.api.state.meta.errorMap // {onChange: "Error" | undefined} -->
<!-- group.api.state.meta.errors // ("Error")[] -->
</ng-container>
`,
})
export class AppComponent {
form = injectForm({
defaultValues: {
step1: { name: '' },
},
})
groupValidator = () => 'Error'
}
- Can set errors on sub-fields:
@Component({
selector: 'app-root',
standalone: true,
imports: [TanStackFormGroup],
template: `
<ng-container
[tanstackFormGroup]="form"
name="step1"
[validators]="{ onChange: groupValidator }"
></ng-container>
`,
})
export class AppComponent {
form = injectForm({
defaultValues: {
step1: { name: '' },
},
})
groupValidator = ({ value }: { value: { name: string } }) => ({
group: value.name === 'error' ? 'Group error' : undefined,
fields: {
// Must use the name of the field relative to the FormGroup as the error key,
// to stay consistent with how standard schema works with form groups
name: value.name === 'error' ? 'Field error' : undefined,
},
})
}
- And can even accept standard schemas:
import { z } from 'zod'
@Component({
selector: 'app-root',
standalone: true,
imports: [TanStackFormGroup],
template: `
<ng-container
[tanstackFormGroup]="form"
name="step1"
[validators]="{ onChange: step1Schema }"
></ng-container>
`,
})
export class AppComponent {
step1Schema = z.object({
name: z.string().min(2),
})
form = injectForm({
defaultValues: {
step1: { name: '' },
},
})
}
The reason we don't use the full path names for fields is so that you can compose your schemas like so:
const step1Schema = z.object({ name: z.string().min(2), }) const schema = z.object({ step1: step1Schema, step2: step2Schema, })And pass the
step1Schemato a form group andschemato the parent form. That way, partially validated data will still flag errors if the group is bypassed.
Dynamic Group Validation
If you want to use dynamic validation (onDynamic) with a form group, do not rely on the onDynamic validator passed to injectForm:
form = injectForm({
validationLogic: revalidateLogic(),
validators: {
// This validator will not run `onChange` when a sub-form is submitted;
// it will only run `onChange` when the form itself is submitted.
onDynamic: schema,
},
})
Instead, pass your sub-schema for the group to the onDynamic validation of the group itself:
@Component({
selector: 'app-root',
standalone: true,
imports: [TanStackFormGroup],
template: `
<ng-container
[tanstackFormGroup]="form"
name="step1"
[validators]="{ onDynamic: step1Schema }"
></ng-container>
`,
})
export class AppComponent {
step1Schema = step1Schema
form = injectForm({
defaultValues: {
step1: { name: '' },
},
})
}
It will treat group.api.submissionAttempts as the way to change what validator is run before/after submit.
Form Group State
Just like you're able to access group.api.state.meta.errors, you're also able to access the group's value using group.api.state.value. Likewise, here are some valuable properties you can access in the group.api.state.meta:
group.api.state.meta.isFieldsValid:truewhen the field-level validators have no errorsgroup.api.state.meta.isGroupValid:truewhen the group-level validators have no errorsgroup.api.state.meta.isValid:truewhen both the field-level and group-level validators have no errorsgroup.api.state.meta.isSubmitting:truewhen the group is in the process of being submitted
