Symfony 2中的Equal Fields验证


Equal Fields validation in Symfony 2

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

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

在"用户"实体中,我没有"confirmPasswod"字段。所以我得到错误:

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

是否有任何方法可以对某些表单字段使用基于实体的表单验证,而不对其他字段使用基于主体的验证?提前谢谢。

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'),    
));