繁体   English   中英

Yii使用用户身份对象在视图中显示用户类型

[英]Yii showing user type in view using user identity object

在我的Web应用程序中,我需要在protected/views/layouts/main.php中显示视图中的用户类型。

但我收到此错误:

"CException" ."Property "CWebUser.type" is not defined."

我无法摆脱此错误,如何解决此问题?

我正在使用此行代码来显示用户类型

array('label'=>'Logout ('.Yii::app()->user->type.')', 'url'=>array('/site/logout'), 
'visible'=>!Yii::app()->user->isGuest)

我也通过使用user-> user_type尝试过,但不起作用

我的UserIdentity class代码

class UserIdentity extends CUserIdentity
{
    private $_id;


    public function authenticate()
    {
        $user = User::model()->findByAttributes(array(
                'email'=>$this->username));
        if ($user === null) {

            $this->errorCode=self::ERROR_USERNAME_INVALID;
        } else if ($user->pass !==
        hash_hmac('sha256', $this->password,
                Yii::app()->params['encryptionKey']) ) {

            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        } else { 
            $this->errorCode=self::ERROR_NONE;
            $this->setState('type', $user->user_type);
            $this->setState('id', $user->id);
            $this->_id = $user->id;

        }
        return !$this->errorCode;

    }

    public function getId() {
        return $this->_id;

    }

}

另外,由于我使用的是基于角色的访问控制,因此我更改了user.php中用于为用户分配角色的代码

我的代码分配用户类型。

public function afterSave() {
        if (!Yii::app()->authManager->isAssigned(
                $this->type,$this->id)) {
            Yii::app()->authManager->assign($this->type,
            $this->id);
        }
        return parent::afterSave();
        }

而且我已经在SiteController中使用了这段代码来为用户分配角色

$auth->assign($user->type,$user->id);

如果我对所发生的事情的理解正确,则有时您可能没有登录,即Yii试图访问用户设置。 由于您尚未登录,因此无法访问它们,因此会出现错误。 因此,在标签中,检查用户isset()

'label' => (isset(Yii::app()->user->type) ? Yii::app()->user->type : '')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM