【问题标题】:Symfony2 form repeated field - how to move 'not matching' message to confirm field?Symfony2 表单重复字段 - 如何将“不匹配”消息移动到确认字段?
【发布时间】:2013-08-10 17:31:39
【问题描述】:

我正在创建一种注册类型的表单,并在其中使用“重复”字段类型来获取用户所需的密码并进行确认。我将此字段添加到我的表单中,如下所示:

$builder->add(
    'password',
    'repeated',
    array(
        'first_options'  => array('label' => 'user.form.password.label'),
        'second_options' => array('label' => 'user.form.password_confirm.label'),
        'invalid_message' => 'user.password_confirm.not_matched',
        'type' => 'password',
    )
);

这很好用——除了当密码不匹配时,“不匹配”错误消息会显示在第一个字段(密码字段)而不是第二个确认字段中。在我看来,让这条消息出现在确认字段中更合乎逻辑 - 但我正在努力寻找实现这一目标的方法?

我认为也许 'error_mapping' 选项是我需要的,但我没有设法完成这项工作,我不确定这是否是我寻找的正确方向?

感谢您的帮助, 马特

【问题讨论】:

  • 手动渲染字段可以解决这种情况。 symfony.com/doc/current/book/…
  • 无论如何我都在手动渲染该字段 - 尽管我不确定它是否有助于解决这个实际问题。我需要有错误,例如根本没有输入密码才能放在第一个字段中,以及确认字段与该字段不匹配等错误。
  • 我最终解决了这个问题,根本不使用重复的字段类型;相反,我创建了两个密码字段并自己进行了比较。我仍然觉得如果我可以使用重复的字段类型来做到这一点会更好。

标签: forms symfony


【解决方案1】:

如果有人仍然对如何完成 sf2 2.7 感兴趣(我不检查旧版本)

        ->add('plainPassword', 'repeated', [
            'type' => 'password',
            'invalid_message' => 'user.password_repeat.not_match',
            'error_mapping' => [
                '.' => 'second'
            ]
        ])

所以我希望它会有所帮助,因为这个任务的谷歌搜索结果仍然会导致这个问题没有正确的答案

【讨论】:

  • 这太棒了。我现在搜索了一个小时。
  • 有谁知道我怎样才能只将不匹配的错误映射到第二个字段?
【解决方案2】:

将确认字段移至第一个选项:

$builder->add(
    'password',
    'repeated',
    array(
        'second_options'  => array('label' => 'user.form.password.label'),
        'first_options' => array('label' => 'user.form.password_confirm.label'),
        'invalid_message' => 'user.password_confirm.not_matched',
        'type' => 'password',
    )
);

并更改模板中的字段顺序

{{ form_row(form.password.second) }}
{{ form_row(form.password.first) }}

【讨论】:

    猜你喜欢
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 2012-03-19
    • 2020-08-24
    • 2016-03-01
    • 1970-01-01
    相关资源
    最近更新 更多