Custom rendering of a “repeated” field from Symfony 2 in Twig

前端 未结 5 1753
南旧
南旧 2020-12-23 20:56

I just started using Twig and I\'m trying to build a registration form. To add a password/re-enter password field I use the \"repeated\" filetype:

->add(\         


        
5条回答
  •  温柔的废话
    2020-12-23 21:43

    If you want to have application wide classes for your labels and inputs, you can customize how labels and widgets are rendered. Check http://symfony.com/doc/current/cookbook/form/form_customization.html

    If you look at this file:

    vendor/symfony/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig
    

    You can see the defaults for all widgets. To achieve specifically what you need, you could override generic_label block to add form-label class:

    {% block generic_label %}
    {% spaceless %}
        {% if required %}
            {# We add form-label class in the next line! #}
            {% set attr = attr|merge({'class': attr.class|default('') ~ ' required form-label'}) %}
        {% endif %}
        {{ label|trans }}
    {% endspaceless %}
    {% endblock %}
    

    And widget_attributes block to add form-input class:

    {% block widget_attributes %}
    {% spaceless %}
        {# We add form-input class in the next line! #}
        {% set attr = attr|merge({'class': attr.class|default('') ~ ' form-input'}) %}
        id="{{ id }}" name="{{ full_name }}"{% if read_only %} disabled="disabled"{% endif %}{% if required %} required="required"{% endif %}{% if max_length %} maxlength="{{ max_length }}"{% endif %}{% if pattern %} pattern="{{ pattern }}"{% endif %}
        {% for attrname,attrvalue in attr %}{{attrname}}="{{attrvalue}}" {% endfor %}
    {% endspaceless %}
    {% endblock widget_attributes %}
    

    With these two templates all your inputs should render with the classes you need, without having to repeat the 'attr' parameters all over your forms.

    I haven't tried it, but this should take care of the repeated field problem. Even if it didn't, you could create a repeated_widget and/or repeated_row template to customize how the repeated widget renders, thus fixing that widget for all the forms that use it.

提交回复
热议问题