Skip to content

Instantly share code, notes, and snippets.

@weaverryan
Forked from inoryy/gist:1540222
Created December 30, 2011 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save weaverryan/1540293 to your computer and use it in GitHub Desktop.
Save weaverryan/1540293 to your computer and use it in GitHub Desktop.

Redirecting to last visited page after registration.

Imagine this scenario: A new user on your awesome webpage finds an awesome link, but it's only open to registered users, so he's automatically redirected to login form, then he goes to a register page (or fills embedded form right there) and then gets redirected back to a homepage. Somewhat frustrating experience, don't you think?

Well, let's solve this little problem with some help from [symfony2 authentication listener] (https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Security/Http/Firewall/AbstractAuthenticationListener.php). More specifically, by exploiting [already existing feature] (https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Security/Http/Firewall/AbstractAuthenticationListener.php#L270) for login form. This feature is actually a simple session parameter that is set the moment you're redirected to login page and purged the moment you login. Thus all you need to do is let symfony do its magic, redirect user to a login page from your private page and if he clicks on register (or fills in embedded form), have this snippet for redirecting URLs:

// ...

use Symfony\Component\Request\Request;

class RegistrationController extends Controller
{
    public function registerAction(Request $request)
    {
        $form = $this->createForm(new SomeRegistrationForm());
        $form->bindRequest($request);

        if ($form->isValid()) {
            // do something awesome, like saving the User created by your registration form
            $user = $form->getData();

            // authenticate your user right now
            $this->authenticateUser($user);

            if ($this->container->get('session')->has('_security.target_path')) {
                $url = $this->container->get('session')->get('_security.target_path');
                $this->container->get('session')->remove('_security.target_path');
            } else {
                $url = $this->container->get('router')->generate('knp_university_homepage');
            }

            return new RedirectResponse($url);
        }

        // .. re-render the form on error
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment