0

Is there a way to access username of the logged user on page, which is accessible to anonym users in Symfony 2.6.1?

Example: I have main page, where is link to login and if there is a user logged in, I want to display his username as a link to his account instead of the login link.

If I use {{ app.user.username }} it will display error

Impossible to access an attribute ("username") on a NULL variable ("")

because app.user is null object on pages with security: false defined is security.yml. It will work only on pages, which needs to be under firewall with no security: false.

AppyGG
  • 381
  • 1
  • 6
  • 12
H.W.
  • 343
  • 1
  • 5
  • 21

3 Answers3

0

Im not sure if i understood your problem correctly, but its true that {{ app.user.username }} throws an exception, because there is not user object if you are not logged in. So just check if the object exists:

{% if app.user is defined %}
    {# link to account #} 
{% else %}
    {# link to login #}
{% endif %}

If this hint is not the exspected one, give us some code.

4lxndr
  • 357
  • 2
  • 12
  • But I want to get username even if "app.user" is not defined. Is it possible? – H.W. Mar 03 '15 at 12:28
  • Then you have to get the user object by id. Something like `$this->getDoctrine()->getRepository('User')->find($id)`. – 4lxndr Mar 03 '15 at 13:20
0

You should try something like this:
set a default value for anonymous :

{{ app.user.username|default('Not Logged') }}
BENARD Patrick
  • 30,363
  • 16
  • 99
  • 105
0

Try this

{{ app.security.getToken().getUser() }}
Gustek
  • 3,680
  • 2
  • 22
  • 36