Symfony2: preventing radio widgets from rendering labels
Asked Answered
J

1

5

I'm attempting to customise the form layouts using Twig in symfony2. I am aiming to render a radio input that looks something like this...

<label class=" required">Label name</label>
<span class="form-radio">
    <input type="radio" name="album_has_subalbums_1" /> Yes
</span>
<span class="form-radio">
    <input type="radio" name="album_has_subalbums_0" /> No
</span>

I have overridden the radio_widget block in my custom form theme as follows

{% block radio_widget %}
{% spaceless %}
    <span class='form-radio'>
        <input type="radio" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
    </span>
{% endspaceless %}
{% endblock radio_widget %}

However, this renders the following markup:

<label class=" required">Label name</label>

<span class="form-radio">
    <input type="radio" id="album_has_subalbums_1" name="album[has_subalbums]" required="required" value="1">
</span>
<label for="album_has_subalbums_1" class=" required">Yes</label>

<span class="form-radio">
    <input type="radio" id="album_has_subalbums_0" name="album[has_subalbums]" required="required" value="0">
</span>
<label for="album_has_subalbums_0" class=" required">No</label>

Basically, for each radio input element its creating a label to identify whether the value for it is Yes or No. I'm working with a pre-existing design so I can't easily tweak the html markup.

How can I prevent the radio inputs from generating the selection texts as labels? I know it calls the field_label block internally, but as you can see my radio_widget doesn't make reference to it, so I'm a little lost as to how to prevent this behaviour.

EDIT:

To be clear, I want the same kind of structure as my first example... I have left out the name and value attributes etc, but obviously its just for demonstration purposes.

Joline answered 29/11, 2011 at 19:45 Comment(0)
P
10

What you need to override is not the radio_widget block, but the choice_widget one:

{% block choice_widget %}
{% spaceless %}
    {% if expanded %}
        <div {{ block('widget_container_attributes') }}>
        {% for child in form %}
            {{ form_widget(child) }}
            {{ child.get('label') | trans }} {# <- this is what you need #}
    {# leave the rest untouched #}

And don't forget to clear the cache for this change to take effect.

Papal answered 29/11, 2011 at 20:35 Comment(1)
child.get('label') didn't work for me, whereas child.vars.label did.Johann

© 2022 - 2024 — McMap. All rights reserved.