Daniel Mensing
Daniel Mensing

Reputation: 964

Symfony2 & Twig, getting user variable

I'm having problems getting a user variable, in Twig. When i'm doing a var_dump(app.user) i get the following:

object(App\Bundle\CoreBundle\Entity\Employee)[1233]
  protected 'id' => int 1
  private 'group' => int 0
  protected 'fullName' => string 'Daniel Mensing' (length=14)
  protected 'username' => string 'dm' (length=2)
  protected 'usernameCanonical' => string 'dm' (length=2)

I've added the "fullName", which was not a part of the FOSUSerbundle.

Now, when i try to output the new variable (fullName) in twig, it tells me it does not exist(??) While the standard variables work fine(username, email..) at first i thought it was because i made fullName private, but doesnt work when protected either. Also in the vardump, they look exactly the same

I'm outputting the variables like this: {{ app.user.username }} or {{ app.user.fullName }}

Any1 can point me in the right direction? Or help explain what i'm doing wrong. Any help is much appreciated :-) Thanks

Upvotes: 0

Views: 782

Answers (3)

Vadim Ashikhman
Vadim Ashikhman

Reputation: 10136

In Twig you can access object variables by several methods:

  • Public variable. user.fullName points directly to user object variable, like if you call $object->fullName in php

  • Public method. user.fullName points to getFullName() method of user object, like if you call $object->getFullName() in php.

So either make fullName public or add getFullName() method (recommended).

Upvotes: 3

moonwave99
moonwave99

Reputation: 22820

protected means that the variabile is available just to same class AND subclasses instances, but not from anywhere else.

Provide you class with a proper public getter, e.g. public function getFullname(){ return $this -> fullName; }.

Upvotes: 2

NHG
NHG

Reputation: 5877

You have to add getter for fullName field in App\Bundle\CoreBundle\Entity\Employee entity:

public function getFullName() {
    return $this->fullName;
}

Upvotes: 1

Related Questions