4

我想在两种情况下更新数据:

  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);
    }
4

2 回答 2

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());
    }
});
于 2013-08-20T08:50:52.107 回答
1

更简单的方法:

/my/Entity/User

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

因此,任何使用带有密码的用户的表单都将按预期工作:)

于 2013-08-20T09:28:10.880 回答