Symfony2 how to render Checkboxes?

梦想的初衷 提交于 2019-11-30 15:49:14
Jakub Zalas

From The Symfony Docs

What you basically need to do is to overload checkbox_widget block.

{% form_theme form _self %}

{% block checkbox_widget %}
{% spaceless %}
    <input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
{% endspaceless %}
{% endblock checkbox_widget %}

Of course you can place your widgets in its own line with CSS (but it's not a Symfony2 question).

A lazier way I found to do this was to iterate through the form/choice array.

At its simplest, rendering a form you might do:

{{ form_widget(form) }}

For a little more granularity, you might do:

{{ form_row(form.itemA) }}
{{ form_row(form.itemB) }}
{{ form_row(form.itemC) }}

But if "itemA" is a multi-choice, you're stuck with the entire list getting rendered on the same line. If you're looking for just a little more granularity before you step up to theming, you can do this:

{% for t in form.itemA %}
{{ form_row(t) }}
{% endfor %}

That'll render each checkbox on its own line, or give you an opportunity to do whatever you want between each item.

As Kuba has said in his answer this sounds partly like a CSS question. Semantically speaking injecting something like a <br /> tag doesn't have much meaning but you can do that if you wish by following the documents in Kuba's answer.

If you wish to write some CSS to get those elements to display line by line you can use this against symfony's default output:

input, label {
    float: left;
}

input {
    clear: left;
}

Of course this will actually cause all input and label tags to float left which might not be suitable to you so you can a) wrap your checkboxes in another div and use a css sub-selector like .checkboxes input, .checkboxes label or b) apply a custom css class to your widgets using:

{{ form_widget(form.name, { 'attr': {'class': 'foo'} }) }}

and the CSS would be the same but instead of input you'd have .foo.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!