how to make form ignore password fields if blank (symfony2 forms)

Viewed 16160

I have a simple user manager in my backend, and I want to be able to edit the user without setting a new password/repeating the old password every time.

Right now if I leave the password fields blank when editing a user, symfony2 complains that a password must be entered, and of course I want this functionality when I register new users, but when I edit them, I'd like for the form to just ignore the password boxes if they aren't filled out.

How is this accomplished?

8 Answers

Symfony 5 method:

Inside a controller class:

/**
 * @Route("/user/{id}/edit")
 */
public function updateUser(
    $id, // See 'Route' annot., needed to `find()` User, adjust to your needs
    User $user,
    Request $request,
    UserPasswordEncoderInterface $passwordEncoder,
    UserRepository $userRepository
): Response {
    $form = $this->createForm(UserFormType::class, $user);

    // if password field is required by default, we have to `add()` it again
    // with `required` set to `false`
    $form->add( 
        'plainPassword',
        PasswordType::class,
        [
            // do not use Constraint NotBlank()
            'required' => false,
            'mapped' => false
        ]
    );

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $entity = $userRepository->find($id); // as above, adjust to your needs

        if (!$entity) {
            throw $this->createNotFoundException('User does not exist!');
        }

        $originalPassword = $entity->getPassword();

        /** @var User $user */
        $user = $form->getData();

        // keep original password if new one isn't provided
        if (!empty($form['plainPassword']->getData())) {
            $user->setPassword(
                $passwordEncoder->encodePassword(
                    $user,
                    $form['plainPassword']->getData()
                )
            );
        } else {
            // set old password
            $user->setPassword($originalPassword);
        }

        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();

        return new Response('User updated!');
    }

    return $this->render(
        'admin/user_edit.html.twig',
        [
            'requestForm' => $form->createView(),
        ]
    );
}
Related