Mr. B. Mr. B. - 2 months ago 26
Twig Question

Symfony/Twig: internal ID for form widgets?

I've to modify the

radio_widget
and would like to give the
<label>
and
<input>
the same ID, which should be unique for each pair.

Currently I'm using random(), but I'd prefer an internal counter, something like
{{loop.index}}
(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 }}" {# ...#}/>
</div>
{%- endblock radio_widget %}


Does anyone know a better solution?

Thanks in advance!

Answer

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 {{ form.vars.id }}.

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.

Comments