Symfony2: How to modify the current user's entity using a form?

后端 未结 2 1051
离开以前
离开以前 2021-01-20 17:42

I am trying to add a simple form to allow my users to edit their profile. My problem is:

Since the entity \"linked\" to the form is the same as the current user obje

2条回答
  •  耶瑟儿~
    2021-01-20 18:29

    I used the same solution as FOSUserBundle, which is calling $em->refresh() on my entity when the form validation fails:

    public function profileAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
    
        $user = $this->get('security.context')->getToken()->getUser();
        $entity = $em->getRepository('AcmeSecurityBundle:User')->find($user->id);
    
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }
    
        $form = $this->createForm(new ProfileType(), $entity);
    
        $request = $this->getRequest();
    
        if ($request->getMethod() === 'POST')
        {
            $form->bindRequest($request);
    
            if ($form->isValid()) {
                $em->persist($entity);
                $em->flush();
    
                return $this->redirect($this->generateUrl('profile'));
            }
    
            $em->refresh($user); // Add this line
        }
    
        return $this->render('AcmeSecurityBundle:User:profile.html.twig', array(
            'entity'      => $entity,
            'form'   => $form->createView(),
        ));
    }
    

    Note that if you are using what is called a "virtual" field in "How to handle File Uploads with Doctrine" (in my case "picture_file" you will need to clear it by hand:

    $em->refresh($user);
    $user->picture_file = null; // here
    

提交回复
热议问题