doumen5895 2017-08-06 06:52
浏览 54

Symfony 3:仅在出现错误时自定义您的类输入字段

Usually we can customize the attribute class of an input field from twig with

{{ form_widget(form.username,{'attr':{
       'class':'input',
       'placeholder':'Write your username'
    }}) }}

But how to add a class depending upon the fact that this field has an error?

For example I want my input tag to have an additional class "is-danger" if there is an error encountered during submission

  • 写回答

2条回答 默认 最新

  • dongmeixi5311 2017-08-06 07:03
    关注

    I found a workaround by setting a variable before:

                {% if form_errors(form.username) is not empty %}
                        {% set class = "input is-danger" %}
                    {% else %}
                        {% set class = "input" %}
                    {% endif %}
                    {{ form_widget(form.username,{'attr':{
                        'class':class,
                        'placeholder':'Write your username'
                    }}) }}
    

    It is a bit cumbersome to post all of that in the template though.

    评论

报告相同问题?