Simple check if form field has errors in Twig template

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 14:49:47

That method does not exist. I typically do {% if form.points.vars.errors|length %}.

better way I found, is to use this kind of code

{% if not form.vars.valid %}
<div class="alert alert-error">
    {{ form_errors(form) }}
</div>
{% endif %}

You can also check for errors when overriding field rendering:

{% block field_row %}
{% spaceless %}    
    <div class="control-group {% if errors %}error{% endif %}">
      {{ form_label(form) }}
      <div class="controls">
        {{ form_widget(form) }}        
        {{ form_errors(form) }}        
      </div>
    </div>    
{% endspaceless %}
{% endblock field_row %}

For deeper form customization I do:

<div class="form-group {% if form.MYFORMINPUT.vars.valid==false %}has-error{% endif %}">
//some twisted divs
{{form_label(form.MYFORMINPUT)}}
{{form_widget(form.MYFORMINPUT)}}
</div>

Sf2.5

Since an empty array resolves to false, you can shorten your existing check to

{% if form.WIDGET_NAME.get('errors') %}

This is what i use :

 <div class="form-group {{ form.brand.vars.errors|length > '' ? 'has-error' }}">

The right code is (for Symfony 3.4):

{% if form.vars.errors|length %}

i have create a twig extension to handle this: my extension

public function hasError($string)
{
    if(strlen($string) > 4)
        return true;
    return false;
}

i use it like this in twig

{{ has_error(form_errors(form.username)) ? form_errors(form.username) : '' }}
adavea

I had a similar problem, but form.points doesn't exist in my twig templates.

I had to get the number of errors in the controller, then pass it into my templates as a variable. $form->getErrors() does not behave as you might expect in your controller though. See this SO question for a function that will get the form errors correctly.

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