---
title: 'Form controls'
description: 'How Radiant form controls reach the form: native events, rui-form and the container, and how to write a custom control.'
order: 4
---

# Form controls

A Radiant form is a `rui-form` from Radiant UI that bridges the form's controls to the engine's [form state](/docs/forms/form-state). `se-form-instance` creates the form's runtime, mounts it and hands its state container to `rui-form` with `ruiForm.connect(container, { formatError, submitHandler, resetHandler })`.

`rui-form` keeps control registration, the control value bridge, native validity, ARIA and presentation. The container owns validation timing, touched and dirty state, defaults and which errors show, so `rui-form` ignores its own `mode`, `defaultValues`, `resolver` and field `rules` while a container is connected. It sends a control's value with `setValue`, its blur with `blur` and its [native validity](/docs/forms/form-state#native-validity) with `reportNative`. `formatError` is the form's [issue formatter](/docs/forms/issue-text), `submitHandler` runs the form's submission and `resetHandler` is `container.reset()`.

You do not call `connect` yourself in a Radiant form. A host that needs the container reads it through `FormController`.

## Native events

Radiant UI's form controls dispatch the platform's events on the element whose value changed, after its `value` is updated:

| Event    | Means                                                                                |
| -------- | ------------------------------------------------------------------------------------ |
| `input`  | The user changed the value. It bubbles and is composed.                              |
| `change` | The user committed the value: a paste, a pick, a drop, or focus leaving the control. |

There is no `detail`: read `host.value` or `host.checked`. A value set from code (a property, a reset, a store write) dispatches nothing. Act only when `event.target` is the control host, or a member input of a wrapper or group, because the events of nested parts also reach ancestors. The forms-radiant widgets (`masked-input`, `phone-input`, `input-otp`, `drop-zone`) follow the same rule, and their views take no element-level `onChange`, `onBlur` or `onFocus`.

`rui-change` is only for Radiant UI components that are not form controls, such as tabs, trees, menus, tables and the calendar. Observe a form's values with `FormController.select` or the native `input` and `change` events.

## Read the form from your own element

`FormController` finds the form a host belongs to through its ancestors, so the element has to be rendered inside the form. Make the signals once, as fields, and read them inside an effect.

```tsx title="radiant-summary.tsx"
import { effect } from '@ecopages/signals';
import * as z from 'zod/mini';
import { defineStatic } from '@schema-engine/forms';
import { selectFieldState } from '@schema-engine/forms/state-container';
import { createRadiantFormEngine, FormController, schemaFormRegistrations } from '@schema-engine/forms-radiant';

/**
 * Counts the contacts and says whether the first one is invalid, from the container of the form it sits in.
 *
 * @remarks
 * The controller finds the form through the host's ancestors, so the element has to be rendered inside the
 * form. The signals are made once, as fields, and read inside an effect that follows them.
 */
class ContactSummary extends HTMLElement {
	readonly form = new FormController(this);
	readonly count = this.form.select((snapshot) => snapshot.rowIds['contacts']?.length ?? 0);
	readonly invalid = this.form.select((snapshot) => selectFieldState(snapshot, 'contacts.0.email').invalid);

	private stop?: () => void;

	connectedCallback() {
		this.stop = effect(() => {
			this.textContent = `${this.count.get() ?? 0} contacts, first invalid: ${this.invalid.get() ?? false}`;
		});
	}

	disconnectedCallback() {
		this.stop?.();
	}
}

customElements.define('contact-summary', ContactSummary);

const SummaryRegistration = defineStatic({
	$type: 'summary',
	schema: z.looseObject({ $type: z.literal('summary') }),
	metadata: { name: 'Summary', category: 'content' },
	render: () => <contact-summary />,
});

export const engine = createRadiantFormEngine({ elements: [...schemaFormRegistrations, SummaryRegistration] });
```

- `form.container` is the container itself, `undefined` until the instance has one. A new config or engine builds a new container, so read it on each use and keep no copy.
- `form.select(selector)` is a signal over a pure selector of the snapshot, and it follows a container that arrives late or is replaced. It reads `undefined` while the form has no container and on the server.
- `form.formatIssue(issue, { path })` is the text the form shows for an issue.

## What a control writes

A registration declares the value its control writes with `value` (see [Submitted values](/docs/forms/form-state#submitted-values)),
and the container holds exactly that: a select with number options holds the number, a single choice is one value, a
slider with one thumb is a number. `rui-form` is connected to the container as it is. Radiant UI's own choice controls
hold text, lists of text or lists of numbers, so each of the `select`, `combobox`, `radio`, `checkbox-group` and `slider`
elements wraps its control in a host (`se-select`, `se-combobox`, `se-radio-group`, `se-checkbox-group`, `se-slider`)
whose `value` is the declared one: the host maps it to and from what the control holds, and dispatches `input` and
`change` on itself. A custom control writes its declared value itself.

## Write a custom control

A control that is not one of Radiant UI's becomes a form control in three steps:

1. Register it with `registerFieldControl` before its field connects, which gives the field value access, name wiring and a `submission` policy.
2. Dispatch `input`, and `change` on commit, on the host itself after `value` holds the new value, with no `detail`.
3. Call `announceControlConnect(this)` when it connects. A field that registered before the control existed then seeds it from the form's value and reads its validity. Every Radiant UI control does. A custom host must, and a native `input`, `select` or `textarea` marked `data-rui-control` announces nothing, so it must already be inside its field when the field connects.

This is a control that picks a tone, with the registration that puts it in a form as an element:

```tsx title="radiant-control.tsx"
import { customElement, prop } from '@ecopages/radiant';
import { FormAssociatedElement, type FormValue } from '@ecopages/radiant/form-associated-element';
import { RuiFieldError } from '@ecopages/radiant-ui/field';
import { announceControlConnect, registerFieldControl } from '@ecopages/radiant-ui/form';
import { RuiLabel } from '@ecopages/radiant-ui/label';
import * as z from 'zod/mini';
import { defineInput, BaseFieldSchema } from '@schema-engine/forms';
import { createRadiantFormEngine, schemaFormRegistrations } from '@schema-engine/forms-radiant';
import { FormField } from '@schema-engine/forms-radiant/primitives';

/**
 * A control that picks one of its options, as a form control of its own.
 *
 * @remarks
 * A form control announces itself when it connects, so a field that registered earlier seeds it, and
 * dispatches the native `input` and `change` on itself after `value` holds the new value. A value set from code
 * dispatches nothing, which is how the form writes a reset or a default into it.
 */
@customElement('x-tone')
export class ToneControl extends FormAssociatedElement {
	@prop({ type: String, reflect: true, defaultValue: '' }) value!: string;

	protected override onConnected(): void {
		super.onConnected();
		announceControlConnect(this);
	}

	choose(value: string): void {
		this.value = value;
		this.dispatchEvent(new InputEvent('input', { bubbles: true, composed: true }));
		this.dispatchEvent(new Event('change', { bubbles: true }));
	}

	protected override formValue(): FormValue {
		return this.value;
	}

	protected override restoreFormState(state: FormValue): void {
		this.value = typeof state === 'string' ? state : '';
	}
}

registerFieldControl('x-tone', {
	read: (host) => (host as ToneControl).value,
	write: (host, value) => {
		(host as ToneControl).value = typeof value === 'string' ? value : '';
	},
	submission: 'host',
});

const ToneSchema = z.extend(BaseFieldSchema, { $type: z.literal('tone') });

export const ToneRegistration = defineInput({
	$type: 'tone',
	schema: ToneSchema,
	value: () => z.string(),
	metadata: { name: 'Tone', category: 'input' },
	render: (config) => (
		<FormField name={config.name}>
			<RuiLabel>{config.label}</RuiLabel>
			<x-tone name={config.name} />
			<RuiFieldError />
		</FormField>
	),
});

export const engine = createRadiantFormEngine({ elements: [...schemaFormRegistrations, ToneRegistration] });
```

`FormField` from `@schema-engine/forms-radiant/primitives` is the field host. Extend `FormAssociatedElement` for the control to take part in a native `FormData` post, and set `submission: 'host'` as above. For a control that is not form-associated, give `registerFieldControl` a `validity` function; for a control with a wrapper or group whose own native inputs dispatch the events, register it with `events: 'members'`. Radiant UI's Form page covers the control protocol in full.

The `engine` here is the engine you give the renderer. Register the element on it as shown, and a form config can use `{ $type: 'tone' }`.
