Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML in Symfony2 form labels instead of plain text

Tags:

php

symfony

I am trying to implement something like this:

<div>
    <input type="checkbox" name="checkbox" id="checkbox_id" />
    <label for="checkbox_id">I agree to the <a href="/tos">Terms of Service</a></label>
</div>

The closest I've come to implement this is through:

<div>
    {{ form_widget(form.agreeWithTos) }}
    <label for="{{ form.agreeWithTos.vars.id }}">I agree to the <a href="#">Terms of Service</a></label>
</div>

Is there a better way? Having to specify {{ form.agreeWithTos.vars.id }} is inelegant. :)

like image 881
asartalo Avatar asked Sep 26 '11 07:09

asartalo


1 Answers

Solved this problem using the following code in my form-theme:

{# ---- form-theme.html.twig #}
{% block checkbox_row %}
{% spaceless %}
<div>
    {{ form_errors(form) }}

    <label class="checkbox" for="{{ form.vars.id }}">
        {{ form_widget(form) }}
        {{ label|default(form_label(form)) | raw }}
    </label>
</div>
{% endspaceless %}
{% endblock %}

in your Form-Template you can then use:

{% form_theme form '::form-theme.html.twig' %}

{{form_row(form.termsOfServiceAccepted, {
        'label' : 'I have read and agree to the <a href="#">Terms and conditions</a>'
    })
}}

this way, the block from the form-theme would apply to any checkbox on the page. If you need to also use the default-theme, you can add a parameter to enable special-rendering:

{# ---- form-theme.html.twig #}
{% block checkbox_row %}
{% spaceless %}
    {% if not useTosStyle %}
        {{ parent() }}
    {% else %}
        {# ... special rendering ... #}
    {% endif %}
{% endspaceless %}
{% endblock %}

which would be used like this:

{% form_theme form '::form-theme.html.twig' %}

{{form_row(form.termsOfServiceAccepted, {
        'useTosStyle' : true,
        'label' : 'I have read and agree to the <a href="#">Terms and conditions</a>'
    })
}}
like image 172
Martin Schuhfuß Avatar answered Oct 22 '22 15:10

Martin Schuhfuß