2012-01-31 84 views
5

我正试图在Symfony 2项目中实现更改密码功能。 我有实体User带有验证规则validation.yml文件。在User实体中,我有字段“password”,其验证约束条件为validation.yml
我创建了2个字段'password'和'confirmPasswod'的表单。我想对“密码”字段使用我的实体验证约束,并检查'​​passwod'和'confirmPassword'字段之间是否相等。在我contronller我写Symfony 2中的等效字段验证

$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 

有没有办法使用某种形式的领域基于实体的表单验证,而不是基于实体的验证为其他? 在此先感谢。

回答

16

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

谢谢,这是非常很有帮助。 – Ris90 2012-01-31 13:52:37

+1

这也适用于我。谢谢。但有一件事我改变了。我使用'password'和'password_confirmation'而不是'Password'和'Password confirmation'。如果你使用后者,你最终会遇到一些尴尬的元素名称,比如'vnn_pressboxbundle_preferencestype_password_Confirm password'。 – 2012-04-01 14:32:59