Symfony 3, populating token and refreshing user Symfony 3, populating token and refreshing user symfony symfony

Symfony 3, populating token and refreshing user


Your user token seems to be updated by the form, even if the email constraint stop the flush.

Can you check if your form past the isValid function ? You can maybe try to avoid it with an event listener or a validator.

With an event SUBMIT you should be able to check the email integrity, and then add a FormError to avoid the refreshUser.


This is a tricky one, thanks to the repository it was easier to isolate the problem. You are binding the user object form the authentication token to the createForm() method. After the

$form->handleRequest($request)

call the email off the token user object is updated.

I first thought to solve this by implementing the EquatableInterface.html in the User entity but this did not work, as the compared object already had the wrong email address set.

It may also be useful to implement the EquatableInterface interface, which defines a method to check if the user is equal to the current user. This interface requires an isEqualTo() method.)

Than I thought about forcing a reload of the user from the db and resetting the security token, but in the it came to my mind, that it might be sufficient to just refresh the current user object from the database in case the form fails:

$this->get('doctrine')->getManager()->refresh($this->getUser());`

In your controller, this would solve your issue.

/** * @Route("/edit_me", name="edit") * @Security("has_role('ROLE_USER')") */public function editMyselfAction(Request $request) {    $form = $this->createForm(User::class, $this->getUser());    if ($request->isMethod(Request::METHOD_POST)) {        $form->handleRequest($request);        if ($form->isSubmitted() && $form->isValid()) {            $user = $form->getData();            $em = $this->getDoctrine()->getManager();            $em->persist($user);            $em->flush();        } else {            $this->get('doctrine')->getManager()->refresh($this->getUser());        }    }    return $this->render(':security:edit.html.twig',['form' => $form->createView()]);}

Alternative solution

The issue at the Symfony repository resulted in some valuable input about Avoiding Entities in Forms and Decoupling Your Security User which provides a more complex approach for a solution to your problem.