# Fields

> The field object, inputProps, number and optional inputs, and binding component libraries.

Source: https://forms.lunarhue.dev/solid/basics/fields

`form.Field` takes a field name and passes that field's object to its child.
The object holds the field's state and commands, and `inputProps` turns it
into the props an input needs. Type a number with a trailing `.` and watch
the line under Age.

```tsx title="profile.tsx"
import { createForm, createForms, inputProps } from "@lunarhue/forms-solid";

const forms = createForms();

interface Profile {
  name: string;
  // Optional: starts out undefined, and an empty input shows it.
  nickname?: string;
  // A number input holds a number, or undefined while it is empty.
  age: number | undefined;
  plan: "free" | "pro";
  newsletter: boolean;
}

const profile = forms.define<Profile>({
  defaultValues: { name: "", age: undefined, plan: "free", newsletter: false },
  onSubmit: (value) => value,
});

export default function ProfileForm() {
  const form = createForm(profile, { id: "profile" });
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          <form.Field name="name">
            {(field) => (
              <label>
                Name
                <input {...inputProps(field)} />
              </label>
            )}
          </form.Field>
          <form.Field name="nickname">
            {(field) => (
              <label>
                Nickname (optional)
                <input {...inputProps(field)} />
              </label>
            )}
          </form.Field>
          <form.Field name="age">
            {(field) => (
              <label>
                Age
                <input {...inputProps(field, { kind: "number" })} />
                <output>Stored: {JSON.stringify(field.value) ?? "undefined"}</output>
              </label>
            )}
          </form.Field>
          <form.Field name="plan">
            {(field) => (
              <label>
                Plan
                <select {...inputProps(field, { kind: "select" })}>
                  <option value="free">Free</option>
                  <option value="pro">Pro</option>
                </select>
              </label>
            )}
          </form.Field>
          <form.Field name="newsletter">
            {(field) => (
              <label>
                <input {...inputProps(field, { kind: "checkbox" })} />
                Send me the newsletter
              </label>
            )}
          </form.Field>
          <button type="submit">Save</button>
        </form>
      )}
    </form.Form>
  );
}
```

```tsx
<form.Field name="age">
  {(field) => <input {...inputProps(field, { kind: "number" })} />}
</form.Field>
```

## The field object

`FieldApi<T>` holds the field's current state, its commands, and the pieces
that bind an element. A new object arrives with each change.

| Member | What it is |
| --- | --- |
| `value` | The value the store holds. |
| `name` | The dotted name with array indexes, such as `tasks.0.title`. |
| `errors`, `shownErrors` | Every error, and the ones the `show` setting lets through now. |
| `userErrors` | The errors set with `setErrors`. They come last in `errors`. |
| `touched`, `edited`, `dirty` | Blurred once, changed by the user, different from the baseline. `dirty` needs the `dirty()` plugin. |
| `invalid`, `validating` | Has any error, has a validator running. |
| `disabled`, `readOnly` | Set on this field or one above it. |
| `setValue`, `setTouched`, `setErrors`, `handleBlur`, `reset`, `validate` | The handle's commands. Arrays add `push`, `insert`, `remove` and `move`. |
| `text`, `setText`, `setNumberText`, `ref` | The pieces for binding an element. See below. |
| `handle` | The field's handle, to pass to another component or keep for later. |
| `id`, `errorId` | Ids for the input and its error list. |

## inputProps

For plain HTML, `inputProps(field)` puts every piece on the element and
adds the rest an `<input>` needs: `name`, `id`, `value`, the change and blur
handlers, `ref`, `disabled`, `readOnly`, and `aria-invalid` and
`aria-describedby` while errors show. It is a function, not a member, so a
form that never calls it doesn't ship it. Pass options for other kinds of
input. The compiler checks them against the field's value type.

| Call | Element | Field type |
| --- | --- | --- |
| `inputProps(field)` or `inputProps(field, { type: "email" })` | `<input>` | string |
| `inputProps(field, { kind: "textarea" })` | `<textarea>` | string |
| `inputProps(field, { kind: "select" })` | `<select>` | string |
| `inputProps(field, { kind: "number" })` or `{ kind: "range" }` | `<input type="number">` or `"range"` | number |
| `inputProps(field, { kind: "checkbox" })` | `<input type="checkbox">` | boolean |
| `inputProps(field, { kind: "checkbox", value })` | one box of a group | array of strings or numbers |
| `inputProps(field, { kind: "radio", value })` | one radio | string, number or boolean |

Number inputs take `empty`, the value an empty input writes. It defaults to
`undefined` and is required when the field's type has no `undefined`.

A component given only a handle records its element with `fieldRef(handle)`
and gets the props from `createInputProps(handle)`.

## Number inputs

A number field bound with `inputProps(field, { kind: "number" })`, or with
`field.setNumberText`, holds a number, or `undefined` while the input is
empty. Some text on the way to a number isn't one yet:

| Typed | Input shows | Field holds |
| --- | --- | --- |
| `12.` | `12.` | `12` |
| `-` | `-` | the value it held before |
| nothing | nothing | `undefined`, or the `empty` option |

`field.text` keeps the typed text while the field still holds the value that
text wrote, so the caret and the `.` don't jump. Once the input loses focus,
or something else writes a different value, it shows the number again.

## Optional fields

An optional field such as `nickname?: string` starts out `undefined`.
`inputProps` shows `undefined` as an empty input, and a checkbox shows it
unticked. Type the form with `define<T>()` to have optional keys, since
`defaultValues` can't leave a key out and still name it:

```ts
interface Profile {
  name: string;
  nickname?: string;
}

const profile = forms.define<Profile>({ defaultValues: { name: "" } });
```

## Components that take a field

The child of `form.Field` can hand the field to your own component. Type its
prop as `FieldApi<T>`, where `T` is the value type it edits:

```tsx
import { type FieldApi, inputProps } from "@lunarhue/forms-solid";

function TextInput(props: { field: FieldApi<string>; label: string }) {
  return (
    <label>
      {props.label}
      <input {...inputProps(props.field)} />
    </label>
  );
}

<form.Field name="name">{(field) => <TextInput field={field} label="Name" />}</form.Field>;
```

Read the field through `props.field`. Destructuring it reads each member once
and the component stops updating.

To skip the `form.Field` wrapper and get `<form.TextInput name="name" />` on
every form, register the component. See
[Reusable field components](https://forms.lunarhue.dev/solid/composition/field-components.md).

## Binding an element

Component libraries such as Base UI, Radix and React Aria own their labels,
ids and aria, and take a value with a change callback. Give them the pieces
of the field object and leave the rest to them:

| Piece | What it does |
| --- | --- |
| `text` | The text to show: number text the user is typing, else the display text a plugin such as a mask gives, else the value. |
| `setText(text, from?)` | Writes typed text. With a mask, it also puts the formatted text in the element and places the caret. `from` is the element or an event whose `target` is the element. Without it, the focused element `ref` recorded is used. |
| `setNumberText(text, empty?)` | Writes text typed in a number field. `-` writes nothing yet, `12.` writes `12`, and empty text writes `empty`. |
| `handleBlur` | Marks the field touched, runs blur validation, and drops typed number text. |
| `ref` | Records the element, so an invalid submit can focus it. |

Checkboxes, switches, selects and radio groups hold a value, not text, so
bind `value` and `setValue`.

The demo binds plain elements the same way a primitive library takes a
field. Type `1.` in Boxes, submit it empty, and clear it.

```tsx title="primitives.tsx"
import { createForm, createForms } from "@lunarhue/forms-solid";
import { CheckboxField, NumberField, TextField } from "./fields";

const forms = createForms();

const order = forms.define({
  defaultValues: { name: "", quantity: undefined as number | undefined, terms: false },
  validate: {
    fields: {
      name: (name) => (name === "" ? { message: "Enter your name." } : undefined),
      quantity: (quantity) =>
        quantity === undefined || quantity < 0.5 ? { message: "Order at least half a box." } : undefined,
      terms: (accepted) => (accepted ? undefined : { message: "Accept the terms." }),
    },
  },
  onSubmit: (value) => value,
});

export default function OrderForm() {
  const form = createForm(order, { id: "primitives" });
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          <form.Field name="name">{(field) => <TextField field={field} label="Name" />}</form.Field>
          <form.Field name="quantity">{(field) => <NumberField field={field} label="Boxes" />}</form.Field>
          <form.Field name="terms">{(field) => <CheckboxField field={field} label="I accept the terms" />}</form.Field>
          <div>
            <button type="submit">Order</button>
            <button type="button" onClick={() => form.root.reset()}>
              Clear
            </button>
          </div>
        </form>
      )}
    </form.Form>
  );
}
```

```tsx title="fields.tsx"
import type { FieldApi, FormError } from "@lunarhue/forms-solid";
import { For } from "solid-js";

interface FieldProps<T> {
  readonly field: FieldApi<T>;
  readonly label: string;
}

// Plain elements bound the way a primitive library takes a field: its text
// or value, the writes, the blur, and `ref` so an invalid submit can focus
// it. A primitive's own value and change props take the same pieces.
function Errors(props: { readonly id: string; readonly errors: readonly FormError[] }) {
  return (
    <ul id={props.id}>
      <For each={props.errors}>{(error) => <li>{error.message}</li>}</For>
    </ul>
  );
}

export function TextField(props: FieldProps<string>) {
  return (
    <div>
      <label for={props.field.id}>{props.label}</label>
      <input
        id={props.field.id}
        ref={props.field.ref}
        value={props.field.text}
        // The event tells a mask where the caret was.
        onInput={(event) => props.field.setText(event.currentTarget.value, event)}
        onBlur={props.field.handleBlur}
        aria-describedby={props.field.errorId}
      />
      <Errors id={props.field.errorId} errors={props.field.shownErrors} />
    </div>
  );
}

export function NumberField(props: FieldProps<number>) {
  return (
    <div>
      <label for={props.field.id}>{props.label}</label>
      <input
        id={props.field.id}
        inputmode="decimal"
        ref={props.field.ref}
        // Keeps "1." and "-" as typed while the field holds 1 and the value before.
        value={props.field.text}
        onInput={(event) => props.field.setNumberText(event.currentTarget.value)}
        onBlur={props.field.handleBlur}
        aria-describedby={props.field.errorId}
      />
      <Errors id={props.field.errorId} errors={props.field.shownErrors} />
    </div>
  );
}

export function CheckboxField(props: FieldProps<boolean>) {
  return (
    <div>
      <label>
        <input
          type="checkbox"
          ref={props.field.ref}
          checked={props.field.value}
          onChange={(event) => props.field.setValue(event.currentTarget.checked)}
          onBlur={props.field.handleBlur}
          aria-describedby={props.field.errorId}
        />
        {props.label}
      </label>
      <Errors id={props.field.errorId} errors={props.field.shownErrors} />
    </div>
  );
}
```

```tsx
<input
  ref={field.ref}
  value={field.text}
  onInput={(event) => field.setText(event.currentTarget.value, event)}
  onBlur={field.handleBlur}
/>

<input type="checkbox" ref={field.ref} checked={field.value} onChange={(event) => field.setValue(event.currentTarget.checked)} />
```

A primitive bound this way shows a reset or a value `persist` restored, since
it reads `text` or `value` on every change. A primitive that keeps its own
text, such as Base UI's `NumberField`, needs `value` and its own change
callback instead of `text`.

A browser can fill inputs back in from before a reload, after the server
markup arrives and before Solid hydrates. `ref` writes the field's state
into a native input, textarea or select when they differ, so the input shows
what the form holds.

## Ids

`field.id` is the form's id followed by the field's path. It stays the same
for the life of the field, including when an array row moves, so it works as
a DOM id and as a list key. The input gets it as `id`, so a
`<label htmlFor={field.id}>` points at the input.

`field.errorId` is the id for the element that lists the field's errors.
`inputProps(field)` points `aria-describedby` at it while errors show, so
screen readers read them with the input. A primitive library that renders
its own error element points at that one instead.
