0
votes

I'm practicing doing a simple Registration form in symfony2. I created a Register model with a plainPassword field and an embedded User document (I'm using mongoDB) and the two FormTypes. The User document has the constraint of NotBlank in the password field.

I wish to read the plainPassword from Register model, hash it and set it to the User document. This is for validating max/min length before hashing.

The problem is, when I bind the form, it seems that Symony already saves an error array with the User.password field being blank. So the form is never valid even when I set the hashed pass after binding. I always receive a "This value should not be blank"

Finally, removing the NotBlank constraint from User.password results in a "You cannot call isValid() on a form that is not bound." Either way I don't wish to remove the constraint, but I wanted to at least see it working.

Some code:

class RegisterController extends Controller {

/**
 * @Route("/register/", name="register_new")
 * @Template()
 */
public function indexAction(Request $request)
{
    $form = $this->createForm(new RegistrationType(), new Registration());

    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);
        $register = $form->getData();
        $user = $register->getUser();
        $user->setPassword(sha1($register->getPlainPassword()));
        $form->setData($register);
        if ($form->isValid()) {
            return $this->redirect($this->generateUrl('login_form'));
        } 
    }
    return array('form' => $form->createView());
}

}
1

1 Answers

2
votes

There are at least two ways of solving this problem:

  • Remove the NotBlank constraint from the password field. The reasoning here is that you don't let users to set their encoded passwords and hence you don't really need to validate it.

    BTW, the error you're getting after removing the constraint is caused not by the fact that you removed it, but by something else.

  • Use validation groups. If you still want to be able to validate the password field somewhere else — in the service layer, for example — create validation groups and exclude constraints of the password field from the group you're using for registration.