Skip to content

Form field attributes

Adding or removing HTML attributes to or from a form field is simple:

$field->setAttribute('data-attribute-address', 'true');
$field->removeAttribute('data-attribute-address');

This also works for Alpine.js or magewire attributes:

$field->setAttribute('@input', 'onChange');
$field->setAttribute(':class', '{"border-red-500": isValid}');
$field->setAttribute('wire:loading.class', 'loading');

To check the current value of an attribute, the getAttributes() method has to be used, which returns an array:

$currentValue = $field->getAttributes()['data-example'] ?? '';

getAttributes()[$code] vs getAttribute($code)

To read an attribute, $field->getAttributes()[$code] must be used. getAttributes returns a map of all currently assigned attributes.
Why not, you might ask, use getAttribute($code)?

The reason is that getAttribute($code) is used to retrieve the EAV attribute model instance for form fields representing EAV attributes.

Setting and removing attributes can be done in any of the form modifier hooks.