Symfony2,FOSuser:编辑输入密码为空的用户


Symfony2, FOSuser : Edit user with empty input password

我正在使用我自己的实体来扩展fos_user。

我实际上是在两个不同的表中扩展User实体(扩展表User的投资者)。一些数据,如密码和电子邮件存储在用户中。投资者可以访问Fos_user方法。

我有一个填充了用户数据的表单。我需要能够在有或没有密码的情况下更新用户。

这是如何做到的:

if(!empty($form->get('password')->getData())){
    $investor->setPlainPassword($form->get('password')->getData());
}

除非密码输入为空,否则更新工作正常。

SQLSTATE[23000]:违反完整性约束:1048列"密码"不能为空

这就是我在表单$builder:中声明输入的方式

->add('password', 'repeated',
            array(
                'type' => 'password',
                'invalid_message' => 'The password fields have to be the same',
                'required' => false,
                'first_options'  => array('label' => 'New password'),
                'second_options' => array('label' => 'Confirm the new password')
            )
        )

这是我的控制器:

public function updateInvestorAction(Request $request)
{
    $user = $this->container->get('security.context')->getToken()->getUser();
    $investor = $this->getDoctrine()->getRepository('AppBundle:Investor')->findOneBy(array('id' => $user->getId()));
    $form = $this->createForm(new UpdateInvestorType(), $investor);
    $form->handleRequest($request);
    if ($form->isValid()) {
        if(!empty($form->get('password')->getData())){
            $investor->setPlainPassword($form->get('password')->getData());
        }
        $em = $this->getDoctrine()->getManager();
        $em->persist($investor);
        $em->flush();
        $session = $this->getRequest()->getSession();
        $session->getFlashBag()->add('message', 'Votre profil a été correctement modifié');
        return $this->redirect($this->generateUrl('home'));
    }
    return array(
        'form' => $form->createView(),
    );
}

如何在不提供新密码或以前的密码的情况下更新我的用户?

我终于找到了一个解决方案:

可以使用setPassword()设置未洗/未洗密码;

因此,如果密码为空,我将使用以前的哈希密码设置密码,这样它就不会再次被哈希。如果它不为空,我将使用setPlainPassword()方法。

这里的新控制器:

public function updateInvestorAction(Request $request)
{
    $user = $this->container->get('security.context')->getToken()->getUser();
    $investor = $this->getDoctrine()->getRepository('AppBundle:Investor')->findOneBy(array('id' => $user->getId()));
    $password = $investor->getPassword();
    $form = $this->createForm(new UpdateInvestorType(), $investor);
    $form->handleRequest($request);
    if ($form->isValid()) {
        if(!empty($form->get('password')->getData())){
            $investor->setPlainPassword($form->get('password')->getData());
        }
        else{
            $investor->setPassword($password);
        }
        $em = $this->getDoctrine()->getManager();
        $em->persist($investor);
        $em->flush();
        $session = $this->getRequest()->getSession();
        $session->getFlashBag()->add('message', 'Votre profil a été correctement modifié');
        return $this->redirect($this->generateUrl('home'));
    }
    return array(
        'form' => $form->createView(),
    );
}