A simple check to see if the form field has errors in the Twig template

In the Twig template, I check if the field has an error, for example:

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

Is there any method like:

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

make it easier? This is not a big difference, but if I cannot make it easier, why not.

+57
symfony twig symfony-forms
Jan 18 2018-12-18T00:
source share
9 answers

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

+81
Jan 18 '12 at 18:35
source share

The best way I've found is to use this kind of code

 {% if not form.vars.valid %} <div class="alert alert-error"> {{ form_errors(form) }} </div> {% endif %} 
+98
Jul 24 '13 at 6:07
source share

You can also check for errors when redefining fields:

 {% 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 %} 
+17
May 16 '12 at 8:42
source share

To further customize the form, 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

+12
Nov 02 '14 at 22:20
source share

Since an empty array resolves to false, you can reduce the existing validation to

 {% if form.WIDGET_NAME.get('errors') %} 
0
Jul 24 '14 at 10:31
source share

This is what I use:

  <div class="form-group {{ form.brand.vars.errors|length > '' ? 'has-error' }}"> 
0
Jul 12 '17 at 10:12 on
source share

The correct code (for Symfony 3.4):

 {% if form.vars.errors|length %} 
0
Dec 20 '18 at 16:59
source share

I had a similar problem, but form.points does not exist in my branch templates.

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

-one
Mar 13 '12 at 23:50
source share

I am creating a branch extension to handle this: my extension

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

I use it like in twig

 {{ has_error(form_errors(form.username)) ? form_errors(form.username) : '' }} 
-2
Aug 04 '14 at 2:00
source share



All Articles