> ## Documentation Index
> Fetch the complete documentation index at: https://anvil.servicetitan.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Form fields

> Bind Anvil2 input fields to formstate with the Form.* wrapper components.

The `Form.*` components bind Anvil2 input fields to a [`formstate`](https://formstate.github.io/) field state, removing the boilerplate of wiring value, change, error, and warning props by hand. Each wrapper is a MobX `observer`, so it re-renders when its bound `A2InputFieldState` changes.

> [!NOTE]
>
> **Changed in 0.9.0:** Selection fields now require selectable field states and
> changed how they store values. See the [migration
> guide](https://anvil.servicetitan.com/docs/kits/common/migration.md#0-8-x-%E2%86%92-0-9-0).

## Installation

Form fields rely on `formstate`, `mobx`, and `mobx-react` as peer dependencies. Install them alongside the package:

```shell theme={null}
npm install @servicetitan/anvil2-ext-common formstate mobx mobx-react
```

## Usage

Create an `A2InputFieldState`, then pass it to the matching `Form.*` component. The wrapper reads `value`, reports validation `error`/`warning`, and writes changes back to the field state.

```tsx theme={null}
import { Form, A2InputFieldState } from "@servicetitan/anvil2-ext-common";

const name = new A2InputFieldState("");
name.validators((value) => !value && "Name is required");

function NameField() {
  return <Form.TextField fieldState={name} label="Name" />;
}
```

The field state is the source of truth. Read `name.value` to get the current value, call `name.validate()` to run validation, and check `name.hasError` / `name.error` to inspect the result. See [Field state](https://anvil.servicetitan.com/docs/kits/common/form-fields/field-state.md) for the full API.

## Owning field states from a screen store

`Form.*` components are binding wrappers, not a form-state framework. For a screen with more than one field, create a MobX class that owns every field state as a class property, plus an aggregate `formstate.FormState` for one-shot validation. Instantiate the store once per component with `useState(() => new Store())` and render it with an `observer` component that binds fields and stays presentational:

```tsx theme={null}
import { useState } from "react";
import { observer } from "mobx-react";
import { FormState } from "formstate";
import {
  Form,
  A2InputFieldState,
  SelectableOptionsFieldState,
} from "@servicetitan/anvil2-ext-common";
import type { SelectFieldOption } from "@servicetitan/anvil2/beta";

class ContactMethodStore {
  name = new A2InputFieldState("");
  contactType = new SelectableOptionsFieldState<SelectFieldOption>(null);

  form = new FormState({ name: this.name, contactType: this.contactType });

  constructor() {
    this.contactType.setOptions([
      { id: "email", label: "Email" },
      { id: "phone", label: "Phone" },
    ]);
  }

  // A class field (not a method) so `this` survives being passed directly
  // to a prop, e.g. `onClick={store.submit}`.
  submit = async () => {
    const result = await this.form.validate();
    if (result.hasError) return;

    await api.saveContactMethod({
      name: this.name.value,
      contactType: this.contactType.value?.id,
    });
  };
}

const ContactMethodForm = observer(function ContactMethodForm() {
  const [store] = useState(() => new ContactMethodStore());

  return (
    <>
      <Form.TextField label="Name" fieldState={store.name} />
      <Form.SelectSync label="Contact type" fieldState={store.contactType} />
      <Button onClick={store.submit}>Save</Button>
    </>
  );
});
```

This mirrors the store pattern used throughout the monolith `app`: the store owns state and mutations, the component only renders and binds.

## Available wrappers

Each wrapper accepts a `fieldState` prop plus the underlying Anvil2 component's props. The field state's value type matches the field:

| Component | `fieldState` value type |
| - | - |
| `Form.DateFieldRange` | `{ startDate, endDate } \| null` |
| `Form.DateFieldSingle` | `string \| null` |
| `Form.DateFieldYearless` | `YearlessDate \| null` |
| `Form.DateFieldYearlessRange` | `{ startDate, endDate }` |
| `Form.NumberField` | `number \| null` |
| `Form.Textarea` | `string` |
| `Form.TextField` | `string` |
| `Form.TimeField` | `string \| null` |

`Form.IntervalFrequency` pairs a numeric interval with a frequency select and binds to a combined `IntervalFrequencyFormState` rather than a single field state — see [Interval frequency](https://anvil.servicetitan.com/docs/kits/common/form-fields/interval-frequency.md).

## Selection fields

`Form.Select`, `Form.MultiSelect`, and `Form.TreeSelect` wrap the beta Anvil2 select components and ship from the package root alongside the rest of the namespace. Both bind to a `SelectableOptionsFieldState` (`Form.Select`) or `SelectableOptionsArrayFieldState` (`Form.MultiSelect`), and never read that field state's `options` — provide a `loadOptions` function instead, and bind the selected option(s) to the field state:

```tsx theme={null}
import {
  Form,
  SelectableOptionsFieldState,
} from "@servicetitan/anvil2-ext-common";
import type { SelectFieldOption } from "@servicetitan/anvil2/beta";

const fruit = new SelectableOptionsFieldState<SelectFieldOption>(null);

const loadOptions = async (search: string) =>
  [
    { id: 1, label: "Apple" },
    { id: 2, label: "Banana" },
  ].filter((option) =>
    option.label.toLowerCase().includes(search.toLowerCase()),
  );

function FruitSelect() {
  return (
    <Form.Select fieldState={fruit} label="Fruit" loadOptions={loadOptions} />
  );
}
```

`Form.Select` and `Form.MultiSelect` support every loader mode. Match the `loadOptions` signature to the `lazy` prop:

| `lazy` prop | `loadOptions` signature |
| - | - |
| *(omitted)* — eager | `(searchValue: string) => Option[] \| Promise<Option[]>` |
| `"page"` | `(searchValue, pageNumber, pageSize) => { options, hasMore } \| Promise<…>` |
| `"offset"` | `(searchValue, offset, limit) => { options, hasMore } \| Promise<…>` |
| `"group"` | `(searchValue, previousGroupKey) => { options, hasMore } \| Promise<…>` |

`"page"` and `"offset"` only support flat option lists. Use `"group"` when options need `groupToString`/`groupSorter`.

If you need `Form.SelectSync` or `Form.MultiSelectSync` instead — the full option set is available client-side — call `fieldState.setOptions()` rather than passing an `options` prop.

## Group fields

Checkbox and radio inputs are provided as the group wrappers `Form.RadioGroup` and `Form.CheckboxGroup`. These render an Anvil2 group with a `FieldMessage`, so validation errors and warnings surface as text. Pass an `items` array; the field state holds the selected option object (`Form.RadioGroup`) or option objects (`Form.CheckboxGroup`), not a bare `id`.

```tsx theme={null}
import {
  Form,
  SelectableOptionsArrayFieldState,
} from "@servicetitan/anvil2-ext-common";

const items = [
  { id: 1, label: "Email" },
  { id: 2, label: "SMS" },
];

const channels = new SelectableOptionsArrayFieldState<(typeof items)[number]>(
  [],
);
channels.validators(
  (value) => value.length === 0 && "Select at least one channel",
);

function ChannelGroup() {
  return (
    <Form.CheckboxGroup fieldState={channels} items={items} legend="Channels" />
  );
}
```

## Limitations

* Single checkbox and radio inputs have no standalone wrapper. Use `Form.CheckboxGroup` or `Form.RadioGroup` — a bare Anvil2 `Checkbox`/`Radio` exposes a boolean error (styling only) with no message area, so the group is the form pattern that renders validation messages.
* The following Anvil2 input types have no `Form.*` wrapper: `SearchField`, `InputMask`, `Switch`, `ButtonToggle`, `SelectCard`, `Combobox`, `SegmentedControl`, and `RichTextEditor`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.