Dawid Ohia
Dawid Ohia

Reputation: 16445

Simple check if form field has errors in Twig template

In Twig template I check if a field has an error like this:

{% if form.points.get('errors') is not empty %}

Is there any method like:

{% if form.points.hasErrors() %}

to do it simpler? It's not a big difference, but if I can't do it easier why not.

Upvotes: 66

Views: 77306

Answers (10)

ebenjs
ebenjs

Reputation: 429

If you are using symfony version >= 4, you can check errors existence with this code

{% if form_errors(registrationForm) %}
    <div class="alert alert-danger">        
        {{ form_errors(registrationForm) }}
    </div>
{% endif %}

Upvotes: 4

Abdulkerim Jemal
Abdulkerim Jemal

Reputation: 67

The simplest way of checking whether the form has an error:

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

{% endif %}

Symfony version >= 4

Upvotes: 2

mrDjouk
mrDjouk

Reputation: 381

This is what i use :

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

Upvotes: 1

adavea
adavea

Reputation: 1602

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.

Upvotes: -2

d3uter
d3uter

Reputation: 767

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

Upvotes: 14

Belga
Belga

Reputation: 1

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) : '' }}

Upvotes: -2

Riccardo Galli
Riccardo Galli

Reputation: 12925

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

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

Upvotes: 0

birko
birko

Reputation: 1356

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 %}

Upvotes: 119

jkucharovic
jkucharovic

Reputation: 4244

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 %}

Upvotes: 18

Kris Wallsmith
Kris Wallsmith

Reputation: 8965

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

Upvotes: 94

Related Questions