Edit user profile using FOS User Bundle

流过昼夜 提交于 2019-12-03 17:08:48

The registration event is fired in your method, this is why the newly created user is logged in automatically.

To avoid this comportment and keep the current user as logged in (don't authenticate the newly created user), remove the following line :

$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

This two lines too :

$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

And this line :

$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

Now you are just creating a new user without telling FOSUserBundle you are in registration.

Update

For the edit part, you have to create a specific method to reproduces the comportment of the editProfile, but for a given user (not the authenticated user).

Try to use the following :

public function editUserAction($id)
{
    $user = $em->getRepository('YourBunde:User')->find($id);

    if (!is_object($user)) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }

    /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
    $formFactory = $this->get('fos_user.profile.form.factory');

    $form = $formFactory->createForm();
    $form->setData($user);
    $form->handleRequest($request);

    if ($form->isValid()) {
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');
        $userManager->updateUser($user);

        $session = $this->getRequest()->getSession();
        $session->getFlashBag()->add('message', 'Successfully updated');
        $url = $this->generateUrl('matrix_edi_viewUser');
        $response = new RedirectResponse($url);

    }

    return $this->render('FOSUserBundle:Profile:edit.html.twig', array(
        'form' => $form->createView()
    ));
}

And the route :

security_edit_profile:
    path:     /users/{id}/edit
    defaults: { _controller: YourBundle:Security:editUser }

Remove from the RegisterAction:

$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!