Symfony: Using the current user object with a form

Recently I’ve been working with Symfony, a powerful and popular PHP framework. I’ve been running into my fair share of problems with the framework, a lot of which stems from lack of content/documentation for Symfony 2.x, so I’ve decided to start writing some blog posts about it.

For the application I’ve been developing (For one of my clients over at Spark Creek), I’ve had to create an edit profile page. Using Symfony’s form builder, I created my own form class but wanted to use the current user object instead of creating a dummy model. The problem I was running into was that whenever I tried changing my email address to one already in use, it would show me an error but it would switch by user account to the user with the email address I entered.

After a bit of research, I discovered that the current user object was being re-saved to the session, and since forms bind data to the entity/model even if it’s invalid, the new email was getting saved. Not to the database, just to the session. A bit more research lead me to a simple fix, if the form validation failed, call refresh() from the Doctrine entity manager. This function restores an entity to it’s original state (From the database). Example below:

<?php

/*
 * This file is part of the ------- application.
 *
 * (c) Brandon Wamboldt <[email protected]>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use App\UserBundle\Form\Type\EditProfileType;

/**
 * Controller for user profile pages like view profile, edit profile and change
 * password
 *
 * @author Brandon Wamboldt <[email protected]>
 */
class ProfileController extends Controller
{
    /**
     * Controller for editing the user's profile page
     *
     * @param  Request $request An HTTP foundation request object
     * @return Response An HTTP foundation response object
     *
     * @access public
     */
    public function editAction(Request $request)
    {
        $user = $this->get('security.context')->getToken()->getUser();

        // Create a new edit profile form
        $form = $this->createForm(new EditProfileType(), $user, ['user' => $user]);

        // Was the form submitted?
        if ($request->getMethod() == 'POST') {
            $form->bind($request);

            if ($form->isValid()) {

                // Save the user
                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $em->flush();

                // Redirect the user
                $this->get('session')->setFlash('notice', 'Your profile has been updated');
                return new RedirectResponse($this->generateUrl('my_profile'));
            } else {

                // Reset to default values or else it will get saved to the session
                $em = $this->getDoctrine()->getManager();
                $em->refresh($user);
            }
        }

        return $this->render(
            'AppUserBundle:Profile:edit.html.twig',
            ['user' => $user, 'form' => $form->createView()]
        );
    }
}

5 Replies to “Symfony: Using the current user object with a form”

  1. I have a similar problem like this. Check this link http://stackoverflow.com/a/39192896/1958355 . By following your(this) post i use $em->refresh($user); It worked only for the default entity items. I extended the entity to myBundle (Here image on OneToOne Relation).

    The image in session changes, while form error, but not form values in session. I hope you can help me on this.

  2. Hnow i! use was simstuff asking yourself how thstarting from is effective for youngsters the adolescent kidsself help anxiety I al able to give some thought to it would be suitable for primary, but a regular of us wonder whavailable regarding early. tech school and also assistance school (I have one regarding each) is enough she include it throughout the woman stop in (an international Workbox Refurnish? ) I have a scabulb-anticipated houseor even a four kids’-start and something on route and i also can not snapshots using a a whole lot lot whole house!

  3. Hi! I understand this is kind of off-topic but I had
    to ask. Does running a well-established website such as yours take a lot of work?
    I’m brand new to blogging however I do write in my journal every day. I’d like to
    start a blog so I can share my experience and views online.
    Please let me know if you have any suggestions or tips
    for brand new aspiring blog owners. Thankyou!

  4. wow, thanks this was the same problem i was having. symfony docs arent that great!!

Leave a Reply