symfony:如何将屏幕放在表单错误上?

Some of my web pages are very long and have a form at the bottom of the page. Upon sending a form that fails validation, I am brought back to the top of the page, which is not very user friendly.

I would want to find a way to, after an error, place the scroll on the error, or at the top of the form at least.

Does anyone know of a way to control this?

I did, using javascript:

{% if not form.vars.valid %}
    window.location.hash = 'form';
{% endif %}

I don"t think it is very clean. Do you know of another way?

You can use the autofocus HTML attribute. There's no need for JavaScript to achieve this.

<input type="text" name="field_name" autofocus>

The attribute can be added like this:

{{ form_row(form.field_name, {'attr': {'autofocus': null}}) }}

A simple implementation that checks for a field-error might look like this:

{% if form.field_name.vars.errors|length %}
  {{ form_row(
       form.field_name, 
       form.field_name.vars|merge({'attr': {'autofocus': null}})
     ) 
  }}
{% else %}
  {{ form_row(form.field_name) }}
{% endif %}

If you don't want to add code to each of your field and need a faster and more general solution, this short script will do the job (tested with Symfony3):

var delay = 0;
var offset = 150;
if ($('body').find("span").hasClass('help-block')) {
     $('html, body').animate({scrollTop: $($(".help-block")[0]).offset().top - offset }, delay);
}

offset allows for a better control of the top position of the target element you're scrolling to (useful if the top of your page is hidden by a fixed nav-bar), and delay allows for a delay before scrolling.