Submitting in Steps
The booking asks for everything on one page, and pressing Book trip on an empty booking shows every error at once, from the destination down to the last traveler. A booking of this length reads better in steps, where the button of each step validates only what that step shows.
Grouping the Dates
Every node in a form can be submitted on its own, so each step needs a node. The destination already has one as a key of the booking, and so do the travelers as a list. Only the dates have none, so they are defined as a group:
import type { Destination } from '../api'
import { arrayOf, defineField, defineGroupWithDeps } from '@formtree/vue'
import { arrayOf, defineField, defineGroup, defineGroupWithDeps } from '@formtree/vue'
import { z } from 'zod'
export const TRIP_TYPE = {
oneWay: 'oneWay',
roundTrip: 'roundTrip',
} as const
const ADULT_AGE = 18
const returnDateField = defineField({
schema: z.iso.date({ error: 'Choose a return date' }),
})
const datesGroup = defineGroup({
schema: z.object({
tripType: z.enum(TRIP_TYPE, { error: 'Choose a trip type' }),
departureDate: z.iso.date({ error: 'Choose a departure date' }),
}),
children: { returnDate: returnDateField },
activeWhen: {
returnDate: ({ value }) => value.tripType == TRIP_TYPE.roundTrip,
},
}) The group takes the return date along, together with the condition that reads the trip type beside it.
Adding the Group to the Booking
In the booking, the group replaces the trip type and the dates, under the key dates:
export const bookingForm = defineGroupWithDeps<BookingDeps>()({
schema: z.object({
tripType: z.enum(TRIP_TYPE, { error: 'Choose a trip type' }),
destination: z.string({ error: 'Choose a destination' }),
departureDate: z.iso.date({ error: 'Choose a departure date' }),
}),
children: { returnDate: returnDateField, travelers: travelersArray },
children: { dates: datesGroup, travelers: travelersArray },
activeWhen: {
returnDate: ({ value }) => value.tripType == TRIP_TYPE.roundTrip,
},
childDeps: {
travelers: ({ value, deps }) => ({
international: deps.destinations.some(
destination => destination.code == value.destination && destination.international,
),
}),
},
})The booking now holds the dates under dates, so their names start with it, such as dates.departureDate.
Why the Destination Stays a Key
A group builds the dependencies of its children from its own keys, so a group beside the travelers could pass them nothing. The destination determines whether the travelers need a passport number, so it stays a key of the booking, the parent of every step.
Submitting One Step
Every node has its own handleSubmit. The current step is kept in a ref, and the destination and the dates each get a submit function that moves on to the next step:
<script setup lang="ts">
import type { OutputOf } from '@formtree/vue'
import type { Destination } from './api'
import { provideFormNode, useForm } from '@formtree/vue'
import { computed, ref, shallowRef } from 'vue'
import { fetchDestinations } from './api'
import { bookingForm, TRIP_TYPE } from './forms/booking'
import SelectField from './select-field.vue'
import TextField from './text-field.vue'
const STEP = {
destination: 'destination',
dates: 'dates',
travelers: 'travelers',
} as const
type Step = (typeof STEP)[keyof typeof STEP]
const TRIP_TYPE_OPTIONS = [
{ value: TRIP_TYPE.oneWay, label: 'One way' },
{ value: TRIP_TYPE.roundTrip, label: 'Round trip' },
]
const destinations = ref<ReadonlyArray<Destination>>([])
const destinationOptions = computed(() =>
destinations.value.map(destination => ({
value: destination.code,
label: destination.city,
})),
)
const form = useForm(bookingForm, {
deps: () => ({ destinations: destinations.value }),
})
provideFormNode(form)
const returnDate = form.field('returnDate')
const returnDate = form.field('dates.returnDate')
const travelers = form.array('travelers')
const step = ref<Step>(STEP.destination)
const booking = shallowRef<OutputOf<typeof bookingForm>>()
const submitDestination = form.field('destination').handleSubmit(() => {
step.value = STEP.dates
})
const submitDates = form.group('dates').handleSubmit(() => {
step.value = STEP.travelers
})
const bookTrip = form.handleSubmit(trip => {
booking.value = trip
})
fetchDestinations().then(list => {
destinations.value = list
})
</script>The submit of a step validates only its node and what is below it, so errors in the other steps neither block it nor become visible. Book trip still submits the whole booking.
Showing One Step at a Time
Each step gets a form of its own that submits it, with a Back button to the previous step:
<template>
<form
v-if="step == STEP.destination"
novalidate
@submit.prevent="submitDestination"
>
<SelectField
name="destination"
label="Destination"
:options="destinationOptions"
/>
<button type="submit">Continue</button>
</form>
<form v-else-if="step == STEP.dates" novalidate @submit.prevent="submitDates">
<SelectField
name="dates.tripType"
label="Trip"
:options="TRIP_TYPE_OPTIONS"
/>
<TextField name="dates.departureDate" label="Departure" type="date" />
<TextField
v-if="returnDate.state.active"
name="dates.returnDate"
label="Return"
type="date"
/>
<div>
<button type="button" @click="step = STEP.destination">Back</button>
<button type="submit">Continue</button>
</div>
</form>
<form v-else novalidate @submit.prevent="bookTrip">
<fieldset v-for="traveler in travelers.items" :key="traveler.key">
<legend>Traveler {{ traveler.index + 1 }}</legend>
<TextField
:name="`travelers.${traveler.index}.fullName`"
label="Full name"
/>
<TextField
:name="`travelers.${traveler.index}.birthDate`"
label="Date of birth"
type="date"
/>
<TextField
v-if="traveler.field('passportNumber').state.active"
:name="`travelers.${traveler.index}.passportNumber`"
label="Passport number"
/>
<button type="button" @click="travelers.remove(traveler.index)">
Remove
</button>
</fieldset>
<button type="button" @click="travelers.push({})">Add traveler</button>
<p>{{ travelers.errorMessage }}</p>
<div>
<button type="button" @click="step = STEP.dates">Back</button>
<button type="submit">Book trip</button>
</div>
</form>
<pre v-if="booking">{{ booking }}</pre>
</template>Going back removes the inputs of a step from the page, but their values stay in the form, so every input shows what it held before.
Trying the Booking
Press Continue without a destination, and only its error is shown. Then choose Tokyo and the dates, add a traveler, and go back a step. Every step keeps its values, and the traveler still asks for a passport number.
<script setup lang="ts">
import type { OutputOf } from '@formtree/vue'
import type { Destination } from './api'
import { provideFormNode, useForm } from '@formtree/vue'
import { computed, ref, shallowRef } from 'vue'
import { fetchDestinations } from './api'
import { bookingForm, TRIP_TYPE } from './forms/booking'
import SelectField from './select-field.vue'
import TextField from './text-field.vue'
const STEP = {
destination: 'destination',
dates: 'dates',
travelers: 'travelers',
} as const
type Step = (typeof STEP)[keyof typeof STEP]
const TRIP_TYPE_OPTIONS = [
{ value: TRIP_TYPE.oneWay, label: 'One way' },
{ value: TRIP_TYPE.roundTrip, label: 'Round trip' },
]
const destinations = ref<ReadonlyArray<Destination>>([])
const destinationOptions = computed(() =>
destinations.value.map(destination => ({
value: destination.code,
label: destination.city,
})),
)
const form = useForm(bookingForm, {
deps: () => ({ destinations: destinations.value }),
})
provideFormNode(form)
const returnDate = form.field('dates.returnDate')
const travelers = form.array('travelers')
const step = ref<Step>(STEP.destination)
const booking = shallowRef<OutputOf<typeof bookingForm>>()
const submitDestination = form.field('destination').handleSubmit(() => {
step.value = STEP.dates
})
const submitDates = form.group('dates').handleSubmit(() => {
step.value = STEP.travelers
})
const bookTrip = form.handleSubmit(trip => {
booking.value = trip
})
fetchDestinations().then(list => {
destinations.value = list
})
</script>
<template>
<form
v-if="step == STEP.destination"
novalidate
@submit.prevent="submitDestination"
>
<SelectField
name="destination"
label="Destination"
:options="destinationOptions"
/>
<button type="submit">Continue</button>
</form>
<form v-else-if="step == STEP.dates" novalidate @submit.prevent="submitDates">
<SelectField
name="dates.tripType"
label="Trip"
:options="TRIP_TYPE_OPTIONS"
/>
<TextField name="dates.departureDate" label="Departure" type="date" />
<TextField
v-if="returnDate.state.active"
name="dates.returnDate"
label="Return"
type="date"
/>
<div>
<button type="button" @click="step = STEP.destination">Back</button>
<button type="submit">Continue</button>
</div>
</form>
<form v-else novalidate @submit.prevent="bookTrip">
<fieldset v-for="traveler in travelers.items" :key="traveler.key">
<legend>Traveler {{ traveler.index + 1 }}</legend>
<TextField
:name="`travelers.${traveler.index}.fullName`"
label="Full name"
/>
<TextField
:name="`travelers.${traveler.index}.birthDate`"
label="Date of birth"
type="date"
/>
<TextField
v-if="traveler.field('passportNumber').state.active"
:name="`travelers.${traveler.index}.passportNumber`"
label="Passport number"
/>
<button type="button" @click="travelers.remove(traveler.index)">
Remove
</button>
</fieldset>
<button type="button" @click="travelers.push({})">Add traveler</button>
<p>{{ travelers.errorMessage }}</p>
<div>
<button type="button" @click="step = STEP.dates">Back</button>
<button type="submit">Book trip</button>
</div>
</form>
<pre v-if="booking">{{ booking }}</pre>
</template><script setup lang="ts">
import { useField } from '@formtree/vue'
interface SelectOption {
readonly value: string
readonly label: string
}
const props = defineProps<{
name: string
label: string
options: ReadonlyArray<SelectOption>
}>()
const field = useField<string>(() => props.name)
</script>
<template>
<label :for="field.id">{{ label }}</label>
<select v-model="field.model" v-bind="field.attrs">
<option :value="undefined" disabled>Choose…</option>
<option v-for="option in options" :key="option.value" :value="option.value">
{{ option.label }}
</option>
</select>
<p :id="field.errorId">{{ field.errorMessage }}</p>
</template><script setup lang="ts">
import { useField } from '@formtree/vue'
const props = defineProps<{ name: string; label: string; type?: string }>()
const field = useField<string>(() => props.name)
</script>
<template>
<label :for="field.id">{{ label }}</label>
<input v-model="field.model" v-bind="field.attrs" :type="type" />
<p :id="field.errorId">{{ field.errorMessage }}</p>
</template>import type { Destination } from '../api'
import { arrayOf, defineField, defineGroup, defineGroupWithDeps } from '@formtree/vue'
import { z } from 'zod'
export const TRIP_TYPE = {
oneWay: 'oneWay',
roundTrip: 'roundTrip',
} as const
const ADULT_AGE = 18
const returnDateField = defineField({
schema: z.iso.date({ error: 'Choose a return date' }),
})
const datesGroup = defineGroup({
schema: z.object({
tripType: z.enum(TRIP_TYPE, { error: 'Choose a trip type' }),
departureDate: z.iso.date({ error: 'Choose a departure date' }),
}),
children: { returnDate: returnDateField },
activeWhen: {
returnDate: ({ value }) => value.tripType == TRIP_TYPE.roundTrip,
},
})
const passportNumberField = defineField({
schema: z.string({ error: 'Enter the passport number' }).trim().min(1, {
error: 'Enter the passport number',
}),
})
interface TravelerDeps {
readonly international: boolean
}
const travelerGroup = defineGroupWithDeps<TravelerDeps>()({
schema: z.object({
fullName: z.string({ error: 'Enter the full name' }).trim().min(1, {
error: 'Enter the full name',
}),
birthDate: z.iso.date({ error: 'Enter the date of birth' }),
}),
children: { passportNumber: passportNumberField },
activeWhen: {
passportNumber: ({ deps }) => deps.international,
},
})
const travelersArray = arrayOf(travelerGroup, {
validate: travelers => {
const hasAdult = travelers.some(traveler => isAdult(traveler.birthDate))
return hasAdult ? undefined : { code: 'Add an adult traveler' }
},
})
interface BookingDeps {
readonly destinations: ReadonlyArray<Destination>
}
export const bookingForm = defineGroupWithDeps<BookingDeps>()({
schema: z.object({
destination: z.string({ error: 'Choose a destination' }),
}),
children: { dates: datesGroup, travelers: travelersArray },
childDeps: {
travelers: ({ value, deps }) => ({
international: deps.destinations.some(
destination => destination.code == value.destination && destination.international,
),
}),
},
})
function isAdult(birthDate: string | undefined) {
if (birthDate == undefined) {
return false
}
const adultSince = new Date(birthDate)
adultSince.setFullYear(adultSince.getFullYear() + ADULT_AGE)
return adultSince <= new Date()
}export interface Destination {
readonly code: string
readonly city: string
readonly international: boolean
}
const LATENCY_MS = 400
const DESTINATIONS: ReadonlyArray<Destination> = [
{ code: 'denver', city: 'Denver', international: false },
{ code: 'seattle', city: 'Seattle', international: false },
{ code: 'lisbon', city: 'Lisbon', international: true },
{ code: 'tokyo', city: 'Tokyo', international: true },
]
export function fetchDestinations(): Promise<ReadonlyArray<Destination>> {
return new Promise(resolve => {
setTimeout(() => resolve(DESTINATIONS), LATENCY_MS)
})
}