I want to update the data in two conditions:
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);
    }
                An easy solution to your problem is to disable the mapping of the password field and copy its value to your model manually unless it is empty. Sample code:
$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 keep your controllers clean:
$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());
    }
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With