Yii::app()->user->isAdmin() is not working properl

2019-07-10 02:56发布

问题:

in my layout page Cmenu visible fn Yii::app()->user->isAdmin() is not working properly when i use Yii::app()->user->isAdmin() in someother view it showing correct value but not working in layout. my code in protected/views/layouts/main.php

    <?php $this->widget('zii.widgets.CMenu',array(
        'items'=>array(
            array('label'=>'Home', 'url'=>array('/site/index'),/*'visible'=>!Yii::app()->user->isGuest*/),
            array('label'=>'Master','url'=>array('/site/master'),'visible'=>Yii::app()->user->isAdmin()),
            array('label'=>'Transaction','url'=>array('/site/transaction'),'visible'=>Yii::app()->user->isAdmin()),
            array('label'=>' Alotted Task','url'=>array('/site/alottedtask'),'visible'=>!Yii::app()->user->isGuest),    
            array('label'=>'Completed Task','url'=>array('/site/completedtask'),'visible'=>!Yii::app()->user->isGuest),
            array('label'=>'Status Update', 'url'=>array('/site/statusupdate'),'visible'=>Yii::app()->user->isAdmin()),

            array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>Yii::app()->user->isGuest),
            array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest)
        ),
    )); ?>

it showing the error like

Trying to get property of non-object

Update:

My error page http://localhost/tracktest/index.php

回答1:

So this is the code that is throwing the "non-object" error:

return intval($user->role) == 1;

This means that when PHP is trying to get the role attribute of the $user object, $user is not actually an object. Looking at your code, this means that either loadUser() is not working correctly, or Yii::app()->user->id is not returning the user ID.

To test this, I would add this to your function so some test variables will be printed out:

function isAdmin() { // this should say "public function", btw
  $testId = Yii::app()->user->id;
  echo $testId;
  print_r(User::model()->findByPk($testId));
  die();
}

This should let you see if you are getting the user ID, and if the user if being loaded properly.

Good luck!



回答2:

Use Yii::app()->user->getName()=='username' if you want to check for specific user.



回答3:

You can try this:
array('label' => 'Master', 'url' => array('/site/master'), 'visible' => Yii::app()->user->checkAccess(array('admin')),



标签: php yii