如何从symfony表单处理程序中的表单中删除空值字段

use*_*165 4 symfony-forms symfony

我想在两个条件下更新数据:

  1. 当用户输入表单中的所有字段时(姓名,电子邮件,密码)
  2. 当用户没有输入密码时(我只需要更新姓名和电子邮件).

我有以下formHandler方法.

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);
    }
Run Code Online (Sandbox Code Playgroud)

Ber*_*sek 6

解决问题的一个简单方法是禁用密码字段的映射,并手动将其值复制到模型,除非它是空的.示例代码:

$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
}
Run Code Online (Sandbox Code Playgroud)

如果您希望保持控制器清洁,也可以将此逻辑添加到表单类型:

$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());
    }
});
Run Code Online (Sandbox Code Playgroud)