0

I am using bootstrap form theming. This is my fields.html.twig form template:

{% block form_row %}
{% spaceless %}
    <div class="form-group {% if errors|length > 0 %}has-error{% endif %}">
        {{ form_label(form, label|default(null), { 'label_attr': {'class': 'control-label'} }) }}
        {{ form_errors(form) }}
        {% set class='' %}
        {% if attr.class is defined %}
            {% set class = attr.class %}
        {% endif %}
        {{ form_widget(form, { 'attr': {'class': 'form-control '  ~ class} }) }}
    </div>
{% endspaceless %}
{% endblock form_row %}

The problem is that it does not respect checkboxes. It renders checkboxes like normal input fields. Any idea how to setup a template for checkboxes based on the above template?

4
  • Can you paste the relevant $builder->add part where you add this form field? Do you have fields.html.twig defined in your config.yml as a twig resource? Commented Jun 18, 2014 at 7:30
  • @DebreczeniAndrás yeah everything works fine, only the checkbox is rendered with the above template. But the checkbox should get a different class, not .form-control but .checkbox Commented Jun 18, 2014 at 7:40
  • I don't understand why it shouldn't be rendered as the block above? You only pasted the form_row block. This will render all your form elements. Did you override any other blocks as well? Especially the ones for the checkbox? Are you adding the attr[class]=checkbox to your field? Commented Jun 18, 2014 at 8:37
  • @DebreczeniAndrás I just override form_row. The checkbox has to be rendered differently because it has another class and it has no wrapping div. Is there a chance to separate form_row and the checkbox template? Commented Jun 18, 2014 at 8:40

1 Answer 1

5

You need to override the checkbox related blocks in your fields.html.twig. Depending on your field type (collapsed, expanded) define the following blocks:

{% block choice_widget_collapsed %}
    {% spaceless %}

    {% endspaceless %}
{% endblock choice_widget_collapsed %}


{% block choice_widget_expanded %}
    {% spaceless %}

    {% endspaceless %}
{% endblock choice_widget_expanded %}

{# you can even override the way options are rendered #}
{% block choice_widget_options %}
    {% spaceless %}

    {% endspaceless %}
{% endblock choice_widget_options %}

For the default implementation and the basis of your field templates can be acquired from the following location:
vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.