Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equal Fields validation in Symfony 2

Tags:

php

symfony

I'm trying to implement change password functionality in Symfony 2 project. I have entity User with validation rules in validation.yml file. In User entity I have field "password" with its validation constraints in validation.yml.
I created form with 2 field 'password' and 'confirmPasswod'. I want to use my entity validation constraints for 'password' field and check equality between 'passwod' and 'confirmPassword' fields. In my contronller I write

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

In 'User' entity I don't have 'confirmPasswod' field. So I get error:

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

Is there any way to use entity-based form validation for some form fields and not entity-based validation for other? Thanks in advance.

like image 334
Ris90 Avatar asked Jan 31 '12 12:01

Ris90


1 Answers

In SymfonyForm\ChangePasswordType you can use something like this:

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

Since Symfony 2.1 you can configure options to avoid broken element name (as mentioned in comment)

$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'),    
));
like image 129
jkucharovic Avatar answered Sep 23 '22 19:09

jkucharovic