1

I'm using Symfony and sfDoctrineGuardPlugin.

How do I display, in a template, the username of the current user ?

I've tried $this->getUser()->getUsername(), but all I get is the error : "Call to undefined method sfPHPView::getUser."

I'm trying to display the username in a layout.php, not in a particular module/template

Manu
  • 4,410
  • 6
  • 43
  • 77
  • Well according to your error, $this does not have a function called getUser(), make sure you are calling it from the right object. – Jose Vega Nov 18 '10 at 14:14
  • you can find answers on that kind of questions in the documentation on the Symfony-project website – Kennethvr Nov 18 '10 at 14:23

2 Answers2

8

In a template (view), use $sf_user:

For the username:

echo $sf_user->getUsername();

For the id:

echo $sf_user->getAttribute('user_id', null, 'sfGuardSecurityUser');

Or, in an action (controller), you can do what you're doing in your question:

$this->username = $this->getUser()->getUsername();

and then $username will be available in your view template.

See template shortcuts in the Symfony docs for other view variable shortcuts.

Tapper
  • 1,393
  • 17
  • 28
richsage
  • 26,912
  • 8
  • 58
  • 65
  • I might be wrong, but I think it's better to not use $sf_user in a template, you can better retrieve all the needed data in an action and then use a variable filled with the data to be used in the template. Just to seperate business and views. – Kennethvr Nov 18 '10 at 14:24
  • 1
    I think it depends how much logic you're going to do in the view - if you're simply displaying the username, then I don't see any harm in it - it's a variable you're echoing out, no additional logic required (same as `echo $myObj->field;` really). If you need to do manipulation on that variable prior to display, then it's better to keep it in the action yes. – richsage Nov 18 '10 at 14:31
  • It causes an error when no user is logged in though ... any ideas ? I tried isset ans is_object, but they seem to always return true. – Manu Nov 18 '10 at 15:44
  • 3
    It's because getUsername() really calls getGuardUser()->getUsername(). As you're not logged in GuardUser is not there. Make a check first with $sf_user->isAuthenticated(). – Jakub Zalas Nov 18 '10 at 15:47
0

Try the following. One of them may work.

$this->getSfGuardUser()
$this->getGuardUser()
$this->getUser()->getSfGuardUser()
$this->getUser()->getGuardUser()
Jason Swett
  • 43,526
  • 67
  • 220
  • 351