Skip to main content

Field Events

You can listen to certain events and manage the state of the form. For example, you can hide some fields when another fields has a certain value.

Usage

Update event

You can listen to the update event:

class Example extends Field
{
public function __construct(string $label, string $name, string $otherResource = null)
{
parent::__construct($label, $name, $otherResource);

$this->onUpdate(function (ManagesForm $form, $value) {
$form->showFields('first_name');
$form->setState('first_name', $value[0] . '.');
});
}
}

Update on init

Sometimes you need your update event to be called immediately when your form is ready (similar to an immediate watcher in Vue).

You can pass a boolean as the second argument to achieve this:

->onUpdate(function (FormState $form, $value) {
if (!!$value) {
$form->hideFields('mailing_plan_delay', 'mailing_delay');
return;
}

$form->showFields('mailing_plan_delay', 'mailing_delay');
}, true)

Trigger a chain reaction

In some cases, you might want to trigger a onUpdate on another field, to cause a chain reaction. There are 2 ways you can achieve this:

->onUpdate(function (FormState $form, $value) {
// By passing `true` as the third parameter:
$form->setState('field_1', 'some value', true);

// By manually triggering:
$form->triggerOnUpdate('field_1', 'some value');
})
warning

Be aware that having fields triggering update events on each other causes an endless loop.

On initial form request

You can listen to the initial form request event on each field by overriding the following method.

public function onInitialFormRequest(ManagesForm $form): void
{
dd($form->getState());
}

This will only be called once when the form is requested.