Symfony: How to place a screen on a form error?
Some of my web pages are very long and shaped at the bottom of the page. After submitting a form that fails validation, I will return to the top of the page, which is not very convenient.
I would like to find a way, by mistake, to place the scroll by mistake, or at least at the top of the form.
Does anyone know how to manage 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 differently?
source to share
You can use autofocus
HTML attribute . This does not require JavaScript.
<input type="text" name="field_name" autofocus>
The attribute can be added as follows:
{{ 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 %}
source to share
If you don't want to add code to each of the fields and need a faster and more general solution, this short script will get the job done (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);
}
Bias
gives you better control over the top position of the target you are scrolling to (useful if the top of the page is covered by a fixed navbar), and delay allows you to pause before scrolling.
source to share