Mr. B. Mr. B. - 1 year ago 138
Twig Question

Symfony/Twig: internal ID for form widgets?

I've to modify the

and would like to give the
the same ID, which should be unique for each pair.

Currently I'm using random(), but I'd prefer an internal counter, something like
(Twig: for), to avoid conflicts.

{% block radio_widget -%}
{% set id = random() %}
<div class="radio">
<label for="radio_{{ id }}">Label for {{ id }}</label>
<input type="radio" id="radio_{{ id }}" {# ...#}/>
{%- endblock radio_widget %}

Does anyone know a better solution?

Thanks in advance!

Answer Source

For every form-widget there already exists a pre-calculated unique id.

See: \Symfony\Component\Form\Extension\Core\Type\BaseType::buildView

In twig this ID is accessible through {{ }}.

In essence the id is just a concatenation of the nested form-type names.

Note that form.vars in general contains all the useful stuff you'd need to do form-customization. It's also the place to put custom values when using FormTypeInterface::buildView or FormTypeInterface::finishView to transport data to the form rendering.