簡體   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