symfony:如何将屏幕放置在表单错误上? [英] symfony: How to place the screen on the form error?

查看:109
本文介绍了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.

有谁知道如何控制它?

我做过,使用javascript:

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?

推荐答案

您可以使用自动对焦 HTML属性。

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

这篇关于symfony:如何将屏幕放置在表单错误上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆