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

时间:2013-06-20 17:13:55

标签: symfony symfony-forms

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

  1. 当用户输入表格中的所有字段(姓名,电子邮件,密码)时
  2. 当用户未输入密码时(我只需更新姓名和电子邮件)。
  3. 我有以下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);
        }
    

2 个答案:

答案 0 :(得分: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
}

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

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

答案 1 :(得分:1)

更简单的方法:

/my/Entity/User

public function setPassword($password)
{
    if ($password) {
        $this->password = $password;
    }
}

因此,任何使用用户密码的表单都将按预期运行:)