Radio Group
A drink order where the drink must be chosen and the milk is optional.
Output
Submit to see the output
Press Order before choosing a drink to see the error of the group. Then choose a milk, switch back to None, and order again. None empties the field, so the milk is left out of the output.
vue
<script setup lang="ts">
import type { OutputOf } from '@formtree/vue'
import { provideFormNode, useForm } from '@formtree/vue'
import { shallowRef } from 'vue'
import RadioField from '../components/radio-field.vue'
import { DRINK, drinkOrderForm, MILK } from '../forms/drink-order'
const DRINK_OPTIONS = [
{ value: DRINK.tea, label: 'Tea' },
{ value: DRINK.coffee, label: 'Coffee' },
]
const MILK_OPTIONS = [
{ value: undefined, label: 'None' },
{ value: MILK.oat, label: 'Oat' },
{ value: MILK.whole, label: 'Whole' },
]
const form = provideFormNode(useForm(drinkOrderForm))
const output = shallowRef<OutputOf<typeof drinkOrderForm>>()
const placeOrder = form.handleSubmit(order => {
output.value = order
})
</script>
<template>
<div class="demo-columns">
<form class="demo-form" novalidate @submit.prevent="placeOrder">
<RadioField name="drink" label="Drink" :options="DRINK_OPTIONS" />
<RadioField name="milk" label="Milk" :options="MILK_OPTIONS" />
<div class="demo-row">
<button type="submit">Order</button>
</div>
</form>
<div class="demo-form">
<p class="demo-hint">Output</p>
<pre class="demo-output">
{{ output ? JSON.stringify(output, null, 2) : 'Submit to see the output' }}
</pre>
</div>
</div>
</template>ts
import { defineGroup } from '@formtree/core'
import { z } from 'zod'
export const DRINK = {
tea: 'tea',
coffee: 'coffee',
} as const
export const MILK = {
oat: 'oat',
whole: 'whole',
} as const
export const drinkOrderForm = defineGroup({
schema: z.object({
drink: z.enum(DRINK, { error: 'Choose a drink' }),
milk: z.enum(MILK).optional(),
}),
})vue
<script setup lang="ts">
import { useField } from '@formtree/vue'
interface RadioOption {
readonly value: string | undefined
readonly label: string
}
const props = defineProps<{
name: string
label: string
options: ReadonlyArray<RadioOption>
}>()
const field = useField<string>(() => props.name)
</script>
<template>
<fieldset v-bind="field.attrs" class="demo-choices" role="radiogroup" tabindex="-1">
<legend>
{{ label }}
<span v-if="field.state.required" aria-hidden="true">*</span>
</legend>
<label v-for="option in options" :key="option.label" class="demo-choice">
<input
v-model="field.model"
type="radio"
:name="field.attrs.name"
:value="option.value"
@blur="field.attrs.onBlur"
/>
{{ option.label }}
</label>
<p :id="field.errorId" class="demo-error">{{ field.errorMessage }}</p>
</fieldset>
</template>