Login / log out menu link

Hi,

I have a quick query (I hope). I am using the following code to help generate some menu links in my navigation.


				array('label'=>'Sign in', 'url'=>array('/site/login'), 'itemOptions'=> array('id'=>'sign_in'), 'active'=>false, 'visible'=>Yii::app()->user->isGuest),

				array('label'=>'Logout ('.Yii::app()->user->firstName.')', 'url'=>array('/site/logout'), 'itemOptions'=> array('id'=>'sign_in'), 'active'=>false, 'visible'=>!Yii::app()->user->isGuest)



Which is great it shows the sign in link when the user is a guest and when the user is logged in it shows the logout(Users First Name) link. But when I actually log out I get this error "CWebUser.firstName" presumably because this code


Logout ('.Yii::app()->user->firstName.')

results in an unknown variable as I assign the firstName from the DB to the session at login.

What’s the Yii way to stop that line failing?? ;D (Having a good time with Yii)

Hi Jonny,

How about providing the full error and possibly your user model?

Hi Angelo,

There full error is


Property "CWebUser.firstName" is not defined.

inside CWebUser this line is highlighted


          return parent::__get($name);

and it is due to this line of code in my main.php layout


 array('label'=>'Logout ('.Yii::app()->user->firstName.')', 'url'=>array('/site/logout'), 'itemOptions'=> array('id'=>'sign_in'), 'active'=>false, 'visible'=>!Yii::app()->user->isGuest)

As I said I believe that to be because once you are logged in I assign your firstName from the database to the Yii::app()->user. But if you are not logged in or then log out Yii:app()->user->firstName doesn’t actually exist. So I just wanted to know how I can overcome this problem the Yii way. As I’m new to Yii.

Here is how I assign the data at login


	public function authenticate()

	{

		$user = Users::model()->findByAttributes(array('email'=>$this->username));


		if ($user===null) { // No user found!

			$this->errorCode=self::ERROR_USERNAME_INVALID;

		} else if ($user->pass !== SHA1($this->password) ) { // Invalid password!

			$this->errorCode=self::ERROR_PASSWORD_INVALID;

		} else { // Okay!

		    $this->errorCode=self::ERROR_NONE;

		    // Store the role in a session:

		    $this->setState('type', $user->type); // store user type

			$this->_id = $user->id; // store user id

			$this->setState('firstName', $user->first_name); // store user's first name

		}

		return !$this->errorCode;

	}



Jonny :slight_smile:

Thanks Jonny,

but when i do logout then i got same error msg like "Property "CWebUser.firstName" is not defined." so where i havr to define for logout

this is because the CWebUser does not have the property named firstName so this is the problem. if you want to access the current user’s name you can use the name property instead of firstName for more details read here