【问题标题】:Equal Fields validation in Symfony 2Symfony 2 中的相等字段验证
【发布时间】:2012-01-31 12:47:26
【问题描述】:

我正在尝试在 Symfony 2 项目中实现更改密码功能。 我在validation.yml 文件中有带有验证规则的实体User。在User 实体中,我有字段“password”,其验证约束位于validation.yml
我创建了带有 2 个字段“password”和“confirmPasswod”的表单。我想将我的实体验证约束用于“密码”字段并检查“passwod”和“confirmPassword”字段之间的相等性。在我的控制器中我写了

$form = $this->createForm(new SymfonyForm\ChangePasswordType(), new Entity\User());
if ($form->isValid())
    {..............}

在“用户”实体中,我没有“确认密码”字段。所以我得到错误:

Neither property "confirmPassword" nor method "getConfirmPassword()" nor method "isConfirmPassword()" exists in class

有什么方法可以对某些表单字段使用基于实体的表单验证,而对其他表单字段不使用基于实体的验证? 提前致谢。

【问题讨论】:

    标签: php symfony


    【解决方案1】:

    SymfonyForm\ChangePasswordType 中,您可以使用如下内容:

    $builder->add('password', 'repeated', array(
        'type' => 'password',
        'first_name' => 'Password',
        'second_name' => 'Password confirmation',
        'invalid_message' => 'Passwords are not the same',
    ));
    

    从 Symfony 2.1 开始,您可以配置选项以避免损坏元素名称(如评论中所述)

    $builder->add('password', 'repeated', array(
        // … the same as before 
        'first_name' => 'passwd',
        'second_name' => 'passwd_confirm',
        // new since 2.1
        'first_options'  => array('label' => 'Password'),
        'second_options' => array('label' => 'Password confirmation'),    
    ));
    

    【讨论】:

    • 谢谢,这很有帮助。
    • 这对我也有用。谢谢。不过,我改变了一件事。我使用passwordpassword_confirmation 而不是PasswordPassword confirmation。如果你使用后者,你最终会得到像 vnn_pressboxbundle_preferencestype_password_Confirm password 这样尴尬的元素名称。
    猜你喜欢
    • 2020-10-24
    • 2014-03-04
    • 1970-01-01
    • 2011-06-27
    • 2021-12-31
    • 1970-01-01
    • 2014-10-07
    • 2012-10-30
    • 2015-02-26
    相关资源
    最近更新 更多