Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set different entry_options for each CollectionType entry in Symfony FormBuilder

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?

like image 613
user2937998 Avatar asked Oct 21 '25 01:10

user2937998


1 Answers

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 !

like image 120
felix Avatar answered Oct 23 '25 16:10

felix