Mirage
Mirage

Reputation: 31568

Not able to get currently logged user in symfony2 controller

I have this code in controller

public function newAction()
    {
$em = $this->getDoctrine()->getEntityManager();
$user = $this->container->get('security.context')->getToken()->getUser();

I am getting this error

Fatal error: Call to a member function getUser() on a non-object in /home/xxxxx/Acme/UserBundle/Controller/UserController.php on line 86

Upvotes: 0

Views: 1875

Answers (3)

voghDev
voghDev

Reputation: 5801

I was having the same issue. My mistake was the following:

security.yml

access_control:
    - { path: ^/admin/*, roles: ROLE_ADMIN }

I had to change the controller where I was having the error from this:

routing.yml (BAD)

admin_bets:
    resource: "@adminBundle/Resources/config/routing/bets.yml"
    prefix:   /bets

to this:

routing.yml (GOOD)

admin_bets:
    resource: "@adminBundle/Resources/config/routing/bets.yml"
    prefix:   /admin/bets

Upvotes: 0

Vitalii Zurian
Vitalii Zurian

Reputation: 17986

It means that your security context was not populated with token. It happens, when route to your action is not behind the firewall.

You should check your firewall pattern in security.yml

Upvotes: 5

Mirage
Mirage

Reputation: 31568

  1. Make Sure you are logged in using the Symfony debug bar. If you can see there as logged then it should work ok

  2. Also have a look if that path is behind firewall. If its not even though You are logged but you will not get the user

Upvotes: 1

Related Questions