Matt Welander
Matt Welander

Reputation: 8548

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

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?

Upvotes: 20

Views: 16856

Answers (8)

long
long

Reputation: 4318

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(),
        ]
    );
}

Upvotes: -1

Alexander Schranz
Alexander Schranz

Reputation: 2450

For the validation use 2 different validation groups and set the correct one by the callable function.

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add(
        'oldPassword',
        PasswordType::class,
        [
            'constraints' => new UserPassword([
                'groups' => 'profile_password',
            ]),
            'mapped' => false,
            'required' => false,
        ]
    );

    $builder->add(
        'plainPassword',
        PasswordType::class,
        [
            'constraints' => new NotBlank([
                'groups' => 'profile_password',
            ]),
            'mapped' => false,
            'required' => false,
        ]
    );
}

/**
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(
        [
            'validation_groups' => function (FormInterface $form) {
                $newPassword = $form->get('plainPassword')->getData();
                $oldPassword = $form->get('oldPassword')->getData();
                if ($oldPassword || $newPassword) {
                    return ['profile', 'profile_password'];
                } else {
                    return ['profile'];
                }
            },
        ]
    );
}

Upvotes: -1

DelphiLynx
DelphiLynx

Reputation: 921

What I did was to leave the UserType as is and only remove the password field in the controller:

/**
 * @Route("/users/edit/{username}", name="user_edit")
 */
public function editAction(Request $request, User $user)
{
    $form = $this->createForm(UserType::class, $user);

    // Remove the password field when editing the user
    // Otherwise it must be entered each time the user is edited
    // We can change the password via a special edit-user-password page
    $form->remove('password');

    $form->handleRequest($request);

    if ($form->isValid()) {
        // ...
    }
}

This way you can have a single UserType, reusable in the editAction and the newAction.

Be sure to add the line $form->remove('password'); before $form->handleRequest($request);.

Upvotes: 2

Diego Castro
Diego Castro

Reputation: 2156

On your entity setter for the password property make it like this:

/**
 * Set password
 *
 * @param string $password
 * @return User
 */
public function setPassword($password)
{
    if (!is_null($password)) {
        $this->password = $password;
    }

    return $this;
}

The trick is to check if the parameter being passed is empty and only setting if it's not.

Upvotes: 16

wesamly
wesamly

Reputation: 1584

There is an article gives many options to achieve your request, from the Symfony2 cookbook, in particular, the section below worked for me:

Customizing your Form based on the underlying Data

Below is the implementation:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    // ...
    $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
        $product = $event->getData();
        $form = $event->getForm();

        // check if the Product object is "new"
        // If no data is passed to the form, the data is "null".
        // This should be considered a new "Product"
        if (!$product || null === $product->getId()) {
            $form->add('name', 'text');
        }
    });
}

Upvotes: 1

Liutas
Liutas

Reputation: 5783

If you need add required option to $options array. Example:

public function buildForm(FormBuilder $builder, array $options)
{   

    $builder
        ->add('username', 'text', array('label' => 'Servernamn '))            
        ->add('plainPassword', 'repeated', array(
                  'type' => 'password', 
                  'first_name' => 'password', 
                  'second_name' => 'repeat_password', 
                  'required' => false,
            ));
}

Upvotes: 4

Matt Welander
Matt Welander

Reputation: 8548

For someone else's reference, I worked this one out this way.

My formType:

public function buildForm(FormBuilder $builder, array $options)
{   

    $builder
        ->add('username', 'text', array('label' => 'Servernamn '))            
        ->add('plainPassword', 'repeated', array('type' => 'password', 'first_name' => 'Lösenord för server ', 'second_name' => 'Upprepa lösenord för server',));

    $builder-> addValidator(new CallbackValidator(function(FormInterface $form){
      $username = $form->get('username')->getData();
        if (empty($username)) {
          $form['username']->addError(new FormError("Du måste ange ett namn för servern"));
        }
    }));

}

My updateAction:

public function updateServerAction($id)
{
    $em = $this->getDoctrine()->getEntityManager();

    $entity = $em->getRepository('BizTVUserBundle:User')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Container entity.');
    }

    $originalPassword = $entity->getPassword(); 

    $editForm   = $this->createForm(new editServerType(), $entity);

    $request = $this->getRequest();

    $editForm->bindRequest($request);

    if ($editForm->isValid()) {

        $plainPassword = $editForm->get('plainPassword')->getData();
        if (!empty($plainPassword))  {  
            //encode the password   
            $encoder = $this->container->get('security.encoder_factory')->getEncoder($entity); //get encoder for hashing pwd later
            $tempPassword = $encoder->encodePassword($entity->getPassword(), $entity->getSalt()); 
            $entity->setPassword($tempPassword);                
        }
        else {
            $entity->setPassword($originalPassword);
        }

        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('Server'));
    }

Thus updating my users password should it be set, otherwise keep the original password.

Upvotes: 27

Sgarz
Sgarz

Reputation: 331

You can do something with

if (empty($password)) {
     //edit the password
}

Try fixing that into your form's PHP.

Upvotes: -5

Related Questions