@gluonjs/molecules


@gluonjs/molecules / packages/molecules/src / FormFieldBinding

Interface: FormFieldBinding<Values, Name>

Type Parameters

Values

Values extends Record<string, unknown>

Name

Name extends FormFieldName<Values>

Properties

error

readonly error: string | undefined


name

readonly name: Name


touched

readonly touched: boolean


value

readonly value: Values[Name]

Methods

setTouched()

setTouched(touched?): void

Parameters

touched?

boolean

Returns

void


setValue()

setValue(value): void

Parameters

value

Values[Name]

Returns

void


unregister()

unregister(): void

Returns

void

Example

Bind one application-rendered field to typed value, touched, and error state:

ts
import { createFormController, type FormController, type FormControllerOptions, type FormErrors, type FormFieldBinding, type FormFieldName, type FormListener, type FormOperationOptions, type FormSnapshot, type FormState, type FormSubmitHandler, type FormSubmitResult, type FormTouched, type FormValidationContext, type FormValidator } from '@gluonjs/molecules';

type Profile = { email: string; name: string };
type SubmitResult = { id: string };
const validate: FormValidator<Profile> = (values, context) => values.email.includes('@') ? {} : { email: 'Enter a valid email.' };
const submit: FormSubmitHandler<Profile, SubmitResult> = async (values, context) => ({ id: values.email });
const options = { initialValues: { email: '', name: '' }, validate, onSubmit: submit } satisfies FormControllerOptions<Profile, SubmitResult>;
const controller: FormController<Profile, SubmitResult> = createFormController(options);
const email: FormFieldBinding<Profile, 'email'> = controller.register('email');
const fieldName: FormFieldName<Profile> = email.name;
const errors: FormErrors<Profile> = controller.state.errors;
const touched: FormTouched<Profile> = controller.state.touched;
const state: FormState<Profile> = controller.state;
const listener: FormListener<Profile> = (nextState) => console.log(nextState.dirty);
const context: FormValidationContext<Profile> = { values: state.values, touched, signal: new AbortController().signal };
const operation: FormOperationOptions = { signal: context.signal };
const snapshot: FormSnapshot<Profile> = controller.snapshot();
const result: FormSubmitResult<SubmitResult> = await controller.submit(operation);
controller.subscribe(listener);
controller.hydrate(snapshot);
console.log(fieldName, errors, context.signal.aborted, result.ok);
controller.dispose();