Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the null value field from form in symfony form handler

I want to update the data in two conditions:

  1. When user enters all the fields in form (Name, email, password)
  2. When user does not enter password (I have to update only name & email).

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);
    }
like image 795
user2506165 Avatar asked Mar 23 '23 11:03

user2506165


1 Answers

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());
    }
});
like image 62
Bernhard Schussek Avatar answered Apr 06 '23 11:04

Bernhard Schussek