laravel-form-builder
laravel-form-builder copied to clipboard
accept closure attributes (eg wrapper.class)
This change accepts attributes to be closures (resolved by Laravel's value()
). That's not useful for most fields, because all context is present where the field is defined. But it is useful for collection
fields, because you define the same attributes for all the items/child forms. This way you can dynamically add different attributes for different items:
class ParentForm {
function buildForm() {
$this->add('items', 'collection', [
'type' => 'form',
'prototype' => false,
'empty_model' => fn() => new ChildModel,
'options' => [
'class' => ChildForm::class,
'wrapper' => [
// current
'class' => 'non-dynamic class',
// new, optional syntax
'class' => function(\Kris\LaravelFormBuilder\Fields\FormField $field) {
$model = $field?->getForm()?->getModel();
return 'use $model->id to add highlight class';
},
],
],
]);
}
}
I use this to highlight some collection items if they contain problems.
$field
is the collection item field. In this case a ChildFormType
because type = form
. It could be a InputType
, which doesn't have a getForm()
and doesn't really know anything useful. It's most useful for child forms.
Why it is not yet merged? It seems to be neat one to be introduced
Because I didn't need it after all, and change is scary.