I'm trying to create multiple HiddenType fields in with Form Builder using CollectionType, to group these fields when I'm dealing with them in my controller. But I want each field to have different attributes. Is it possible to use entry_options to set different options for each entry?
I'm using a javascript drag and drop plugin to drop elements in a container, when these elements are dropped a JS code updates these hidden fields that, I use to capture the information in my controller. So is mandatory that these fields are grouped somehow so I can deal with them easily in my controller.
An example:
$builder->add(self::FIELD_MAPPED_COLUMNS, CollectionType::class, [
'entry_type' => HiddenType::class,
'data' => ['field1', 'field2', 'field3'],
'label' => false,
'entry_options' => [
'attr' => [
'data-my-field' => '?????'
]
]
])->add('submit', SubmitType::class);
I want to set a different data-my-field for each HiddenType so I can use it in Javascript. Is it possible?
I just faced the same problem. Here is my workaround.
First add a template in the entry_options:
$builder->add(self::FIELD_MAPPED_COLUMNS, CollectionType::class, [
'entry_type' => HiddenType::class,
'data' => ['field1', 'field2', 'field3'],
'label' => false,
'entry_options' => [
'attr' => [
'data-my-field' => '%templateForMyFieldByFieldData%'
]
]
])->add('submit', SubmitType::class);
Then render each field of the collection individually in a Twig loop and replace the template by the required value:
...
{{ (form_widget(field) | replace('%templateForMyFieldByFieldData%', valueToInsert)) | raw }}
...
Hopefully it will be usefull to someone !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With