1
votes

I am working with session variable in YII framework.

I have created session variable in Site controller

as like

public function authenticate()
{
    $user=UserSignupForm::model()->findByAttributes(array('emailid'=>$this->username));
    if($user===null)
        $this->errorCode=self::ERROR_USERNAME_INVALID;
    else if ($user->password!==($this->password))
        $this->errorCode=self::ERROR_PASSWORD_INVALID;
    else {
        $connection=Yii::app()->db;
        $sql="select rolename from rolesinfo where roleid IN (select roleid from     userroles where userid IN (select userid from userinfo where emailid='$user->emailid')) ";
        $command = $connection->createCommand($sql);
        $roles = $command->queryAll();
        // $this->setState('roles',$roles['0']['rolename']);
        // $this->setState('user', $user->username);
        $this->errorCode=self::ERROR_NONE;
        Yii::app()->session['role1']=$roles['0']['rolename'];
        $s=Yii::app()->session['role1'];
    }
}

I am getting session value within this controller.

But I redirected to another controller. Its session variable not retained and its get destory.

Please suggest any idea.

1
how are you fetching session value in another controller..? - Sudhir Bastakoti
if(Yii::app()->session['role1']=='admin') {} - Sampathkumar
instead of doing in controller you can make it up in user identity class and merge the session variable in the user variable,access via Yii::app()->user->yourvariable - Sudhanshu Saxena
ya you are right But scope destroyed when redirect method called. - Sampathkumar

1 Answers

0
votes

I thinks this link can help you: Yii 1.1: Add information to Yii::app()->user by extending CWebUser

Have a great day.

basically:

  1. put id by session see: Yii 1.1: How to add more information to Yii::app()->user
  2. create class WebUser extends CWebUser in components or other visible folder, something like this:

class WebUser extends CWebUser {

  // Store model to not repeat query.
  private $_model;

  // Return first name.
  // access it by Yii::app()->user->first_name
  function getFirst_Name(){
    $user = $this->loadUser(Yii::app()->user->id);
    return $user->first_name;
  }

  // Return first name.
  // access it by Yii::app()->user->first_name
  function getRole1(){
    $user = $this->loadUser(Yii::app()->user->id);
    #find role
    return $role; #return role
  }

  // Load user model.
  protected function loadUser($id=null)
    {
        if($this->_model===null)
        {
            if($id!==null)
                $this->_model=User::model()->findByPk($id);
        }
        return $this->_model;
    }
}
?>