Skip to content

Passing an Answer to Each Row ​

A trip abroad needs a passport number from every traveler, and only the destination tells whether the trip goes abroad. The group of a traveler sees only its own values, so the booking has to hand the answer down to every row.

Declaring What a Traveler Needs ​

A definition that needs data from its parent declares that data as dependencies. The traveler is defined with defineGroupWithDeps and the type of the data, which then activates the passport number:

forms/booking.ts
ts
import { arrayOf, defineField, defineGroup } 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 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 = defineGroup({ 
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, 
  }, 
})

Every function in the options receives deps, so the passport number applies only while international is true.

Handing the Answer to the Rows ​

A group hands its children their dependencies with childDeps, which the booking builds here from its own destination:

forms/booking.ts
ts
const INTERNATIONAL_DESTINATIONS = ['lisbon', 'tokyo'] 

export const bookingForm = defineGroup({
  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 },
  activeWhen: {
    returnDate: ({ value }) => value.tripType == TRIP_TYPE.roundTrip,
  },
  childDeps: { 
    travelers: ({ value }) => ({ 
      international: INTERNATIONAL_DESTINATIONS.some(code => code == value.destination), 
    }), 
  }, 
})

The list passes them on to every traveler, so choosing Lisbon activates the passport number in every row at once.

Why Data Flows Down

Dependencies flow only from a parent to its children, and a row never reads the form around it. The definition of the traveler works in any form that tells it whether the trip is international, and the booking determines that in one place.

Showing the Passport Number ​

Each of the travelers.items is the node of a traveler, so its passport number is rendered while it is active:

vue
<template>
  <form novalidate @submit.prevent="bookTrip">
    <SelectField name="tripType" label="Trip" :options="TRIP_TYPE_OPTIONS" />
    <SelectField
      name="destination"
      label="Destination"
      :options="DESTINATION_OPTIONS"
    />
    <TextField name="departureDate" label="Departure" type="date" />
    <TextField
      v-if="returnDate.state.active"
      name="returnDate"
      label="Return"
      type="date"
    />

    <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>

    <button type="submit">Book trip</button>
  </form>
  <pre v-if="booking">{{ booking }}</pre>
</template>

A traveler added to an international trip asks for the passport number from the start.

Trying the Booking ​

Live examplePassport numbers for trips abroad

Add two travelers and choose Lisbon. Both ask for a passport number, and choosing Denver deactivates them again.

vue
<script setup lang="ts">
import type { OutputOf } from '@formtree/vue'
import { provideFormNode, useForm } from '@formtree/vue'
import { shallowRef } from 'vue'
import { bookingForm, TRIP_TYPE } from './forms/booking'
import SelectField from './select-field.vue'
import TextField from './text-field.vue'

const TRIP_TYPE_OPTIONS = [
  { value: TRIP_TYPE.oneWay, label: 'One way' },
  { value: TRIP_TYPE.roundTrip, label: 'Round trip' },
]

const DESTINATION_OPTIONS = [
  { value: 'denver', label: 'Denver' },
  { value: 'seattle', label: 'Seattle' },
  { value: 'lisbon', label: 'Lisbon' },
  { value: 'tokyo', label: 'Tokyo' },
]

const form = useForm(bookingForm)
provideFormNode(form)
const returnDate = form.field('returnDate')
const travelers = form.array('travelers')
const booking = shallowRef<OutputOf<typeof bookingForm>>()

const bookTrip = form.handleSubmit(trip => {
  booking.value = trip
})
</script>

<template>
  <form novalidate @submit.prevent="bookTrip">
    <SelectField name="tripType" label="Trip" :options="TRIP_TYPE_OPTIONS" />
    <SelectField
      name="destination"
      label="Destination"
      :options="DESTINATION_OPTIONS"
    />
    <TextField name="departureDate" label="Departure" type="date" />
    <TextField
      v-if="returnDate.state.active"
      name="returnDate"
      label="Return"
      type="date"
    />

    <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>

    <button type="submit">Book trip</button>
  </form>
  <pre v-if="booking">{{ booking }}</pre>
</template>
vue
<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>
vue
<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>
ts
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 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' }
  },
})

const INTERNATIONAL_DESTINATIONS = ['lisbon', 'tokyo']

export const bookingForm = defineGroup({
  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 },
  activeWhen: {
    returnDate: ({ value }) => value.tripType == TRIP_TYPE.roundTrip,
  },
  childDeps: {
    travelers: ({ value }) => ({
      international: INTERNATIONAL_DESTINATIONS.some(code => code == value.destination),
    }),
  },
})

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()
}

Released under the MIT License.