laravel-form-builder icon indicating copy to clipboard operation
laravel-form-builder copied to clipboard

accept closure attributes (eg wrapper.class)

Open rudiedirkx opened this issue 2 years ago • 2 comments

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.

rudiedirkx avatar Oct 15 '22 15:10 rudiedirkx

Why it is not yet merged? It seems to be neat one to be introduced

Eloar avatar Apr 12 '23 07:04 Eloar

Because I didn't need it after all, and change is scary.

rudiedirkx avatar Apr 12 '23 11:04 rudiedirkx