Reputation:
I have a login page that when logged in, returns a welcome page with the name of the user on it. I use this code to pass the variable $user to the welcome page:
return $this->render('LoginLoginBundle:Default:welcome.html.twig', array('user' => $user));
Now on the welcome page I have a nav, with the link to manager.html.twig on it.
This is the code of the link on the welcome page:
<li><a href="{{path('login_login_managerPage')}}">Manager</a></li>
The link goes to this route:
login_login_managerPage:
path: /managerPage
defaults: { _controller: LoginLoginBundle:Default:manager }
which points to the managerAction:
public function managerAction(Request $request) {
$session = $this->getRequest()->getSession();
$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('LoginLoginBundle:User');
if ($session->has('login')) {
$login = $session->get('login');
$username = $login->getUsername();
$password = $login->getPassword();
$user = $repository->findOneBy(array('username' => $username, 'password' => $password));
if ($user) {
return $this->render('LoginLoginBundle:Default:manager.html.twig', array('user' => $user));
}
}
return $this->render('LoginLoginBundle:Default:login.html.twig');
}
Now I can't get $user to the managerpage. How can I pass it properly between pages?
EDIT: I editedy code but now I get this error:
Impossible to access an attribute ("username") on a NULL variable ("") in LoginLoginBundle:Default:welcome.html.twig at line 10
Upvotes: 1
Views: 1173
Reputation: 2576
Instead of writing your own security system, I would recommend you to use Symfony's own security component which has all the important things already done. Please read carefully this link : http://symfony.com/doc/current/book/security.html
Starting from here http://symfony.com/doc/current/book/security.html#using-a-traditional-login-form it shows how to get the user from a database. If you use symfony's security component then you will be able to get current logged in user as follows:
public function indexAction()
{
$user = $this->get('security.context')->getToken()->getUser();
}
In a controller this can be shortcut to:
public function indexAction()
{
$user = $this->getUser();
}
And last in template if you are using twig:
<p>Username: {{ app.user.username }}</p>
Upvotes: 3