My question is how can I access the logged in user from the view? I know it's possible with twigs {app.user}, but I have to do it in php template. Is it possible to get the user from php template? Something like $app->getUser() or something?
2 Answers
You can access the user through the security.context service. For example, you could write in your controller:
$User = null;
$securityToken = $this->container->get('security.context')->getToken();
if (is_object($securityToken) && is_callable([$securityToken, 'getUser']))
$User = $securityToken->getUser();
Note: It is possible that the $User variable does not really contain your user entity. In this case, you should additionally check that $User is an instance of your user entity:
… && is_object($User) && is_callable([$User, 'getId']) && $User->getId() …
Comments
To allow the user to log in using Twig templates magic method {{ app.user.username }}
1 Comment
Krisztián Dudás
Yes, I understand, but I use php templating. Whatever, It turned out, I can access the service container from the view too, so I can call for the
$user = $this->container->get('security.context')->getToken()->getUser() methods, that returns the user.