How to remove a null field from a form in a symfony form handler

I want to update the data in two conditions:

  • When the user enters all the fields in the form (name, email address, password)
  • When the user does not enter a password (I should only update the name and email address).

I have the following formHandler method.

 public function process(UserInterface $user) { $this->form->setData($user); if ('POST' === $this->request->getMethod()) { $password = trim($this->request->get('fos_user_profile_form')['password']) ; // Checked where password is empty // But when I remove the password field, it doesn't update anything. if(empty($password)) { $this->form->remove('password'); } $this->form->bind($this->request); if ($this->form->isValid()) { $this->onSuccess($user); return true; } // Reloads the user to reset its username. This is needed when the // username or password have been changed to avoid issues with the // security layer. $this->userManager->reloadUser($user); } 
+4
source share
2 answers

A simple solution to your problem is to turn off the display of the password field and manually copy its value into your model if it is not empty. Code example:

 $form = $this->createFormBuilder() ->add('name', 'text') ->add('email', 'repeated', array('type' => 'email')) ->add('password', 'repeated', array('type' => 'password', 'mapped' => false)) // ... ->getForm(); // Symfony 2.3+ $form->handleRequest($request); // Symfony < 2.3 if ('POST' === $request->getMethod()) { $form->bind($request); } // all versions if ($form->isValid()) { $user = $form->getData(); if (null !== $form->get('password')->getData()) { $user->setPassword($form->get('password')->getData()); } // persist $user } 

You can also add this logic to your form type if you prefer to clean the controllers:

 $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormInterface $form) { $form = $event->getForm(); $user = $form->getData(); if (null !== $form->get('password')->getData()) { $user->setPassword($form->get('password')->getData()); } }); 
+5
source

A simple way:

 /my/Entity/User public function setPassword($password) { if ($password) { $this->password = $password; } } 

Thus, any form using a user with a password will act as expected :)

+1
source

Source: https://habr.com/ru/post/1487343/


All Articles