How do I apply custom rendering to all form fields except for certain field types in a Symfony 2.1 project

StackOverflow https://stackoverflow.com/questions/19343293

  •  30-06-2022
  •  | 
  •  

Question

I have created a form theme for my project with the following contents:

{% block field_row %}
<div class="row">
    {{ form_errors(form) }}
    {{ form_label(form) }}
    {{ form_widget(form, { 'attr': {'class': 'form-control'} }) }}
</div>
{% endblock field_row %}

I apply this theme to the project globally and now all my form fields get the additional css class 'form-control'.

I now however want to limit this override to only form fields that are not choice & checkbox field types. How do I do this?

Was it helpful?

Solution

I was a bit annoyed when I did something similar as it was more complicated than I thought it should have been. There may be a better way but this is what worked for me.

{% block form_row %}
    {%  set choice = false %}
    {% if not form.vars.compound %}
        {% for prefix in form.vars.block_prefixes %}
            {% if prefix == 'choice' %}
                {%  set choice = true %}
            {% endif %}
        {% endfor %}
    {% endif %}
    {% if choice %}
        <div class="row">
            {{ form_label(form) }}
            {{ form_errors(form) }}
            {{ form_widget(form) }}
        </div>      
    {% else %}       
        <div class="row">
            {{ form_errors(form) }}
            {{ form_label(form) }}
            {{ form_widget(form, { 'attr': {'class': 'form-control'} }) }}
        </div>  
    {% endif %}   
{% endblock form_row  %}

I would recommend using form_row instead of form_field to ease any future transition to to 2.3+ as form_field has been remove from symfony 2.3+ but form_row works in 2.1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top