I would like a <select> element to be rendered with additional data on its <option>s. For the sake of example, I'd like to have a service-selector (non-multiple entity-field) that resets another inputs value upon selection change. I'm not interested in using JS data-structures, I need to have the rendered field to look as follows:
<select name="...">
    <option value="1" data-price="90">Service 1</option>
    <option value="2" data-price="40">Service 2</option>
</select>
I would take two different solutions and would be glad to see the answer to both of them.
form variable I passed to the twig. I have two problems solving this. A) I can't find a safe way to tell what the filed should be named, i.e. how do I get the name attribute that Symfony expects by using the variable form.service (service is the name of the field in the FormType). [Please spare me tricks that concatenate some values based on observing how fields are currently named by Symfony; one should rely on interfaces and not on reverse engineering.] B) I don't know how to access the list of choices, i.e. the array assembled by the entity field's query_builder option. [Since I'm looking for a general solution, I'm not willing to duplicate these items over to a twig-parameter in the controller -- just to avoid such suggestions.]data- attributes are to be rendered, but I don't know how to do this. And finally C) in those cases where I don't need to deviate from standard rendering (e.g. when the field is multiple) I don't know how to fallback to the default rendering.So these are actually 5 questions (1A,1B,2A,2B,2C) but I thought them to be more useful to others answered together, since they all address what I think is an undocumented spot regarding choice field rendering.
You can use the choice_attr option in the form builder:
$builder->add('myField', ChoiceType:class, [
        ....
        'choice_attr' => function($val, $key, $index) {
            return ['data' => '...', 'class' => '', ... etc ];
        },
        ....
]);
This will apply attributes to each option, checkbox, radio in your choice (depending on your expanded and multiple option choices)
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