0

I'm new to Symfony (working on my first project!) and I want to send the user back to the login page with an error saying "You aren't logged in" in case they aren't.

Is there any way to run something so that it changes the user's URL from /secured to /login and send data exactly like:

return $this->render('radloginBundle:Default:login.html.twig',array('errors'=>'You aren\'t logged in'));

So that in the login.html.twig, I have:

{% if errors is defined %}
<div class="red">{{errors}}</div>
{% endif %}

And it will show the user the error message?

I've heard of a method where you can do this:

return $this->redirect($this->generateUrl('radlogin_login',array('errors'=>'You aren\'t logged in')));

But the user's url turns into:

http://.../app_dev.php/login?errors=You+aren't+logged+in

instead of:

http://.../app_dev.php/login
1
  • 1
    Set a flash message and throw a AccessDeniedException Commented Jul 12, 2013 at 23:19

1 Answer 1

1

You can use the flash bag of the session service to pass values through a single request (a redirection really).

The chapter about flash messages can be found in the Symfony documentation.

If the doc isn't enough, here is a code sample:

public function updateAction()
{
    // if the method returns null, the user isn't logged in
    if ($this->getUser() === null) {
        $this->get('session')->getFlashBag()->add(
            'errors', // this is a key
            'You are not logged in' // this is a value to add to key
        );

        // this will redirect to the login page if the user isn't logged in
        throw new \Symfony\Component\Security\Core\Exception\AccessDeniedException();
    }
}

Then you can use the method explained in the documentation to show the errors.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.