Trouble to get user id as session id in yii2

Hi Experts,

I am trying to bind the user is as session id. but getting some error can you help me out???

Situation:

I have a user registration form. On register, it will redirect to another page, where user need to make some selection for there preferences.

I want to get the user registration id as the session id and want to store it to the table associated with preference page.

Once the user preferences is selected, session will terminated and pressing back button will not redirect to the user registration page. If they want to select preference again, then they have to register once again.

Registration form controller code:




{

        $model = new UserRegForm();

        if ($model->load(Yii::$app->request->post())) {

            if ($user = $model->signup())  {

              Yii::$app->session->getuser_id;}

              {

              

                   return $this->redirect(['preference/preferences']);

                

              }


            }

            

        return $this->render('UserReg', [

           'model' => $model,

        ]);

    }



Any idea?

Thanks in advance,

Regards,

Sid

You can go two (maybe more) ways.

  1. Set some session variable, for example Yii::$app->session->set(‘settings-are-not-filled’, true);

  2. Set status for user in db (better, because after logout this settings will work).

In both cases you create, for example, parent FrontendController::init() and check it.




public function init() {

  parent::init();


  if(Yii::$app->request->pathInfo != 'enter/settings') {

    if(Yii::$app->session->get('settings-are-not-filled')) { // or by status

      return $this->redirect('enter/settings');

    }

  }


  return true;

}



Why not just pass it as a GET parameter in the redirect? something like




//do the registration here

//.....

//....

return $this->redirect(['/preferences/user', 'id'=>$YOUR-ID-HERE]);



In case you want to register ID once, check the passed ID and if exists then redirect user to registration page

Hello Stefano,

Can you guide me if i want to view this id in user page (redirected page), how to echo it, in that redirected page?? If I want to bind this "YOUR-ID-VALUE" with the model of the redirected page "user" for saving in the table, which is related to the "user" view, how can i do that?

Regards

Sid

Can you post your current code and point exactly where you are failing?

User Registration action:




public function actionUser()

   

    {

     $model = new UserForm();

        if ($model->load(Yii::$app->request->post())) {

            if ($user = $model->signup())  {

                      return $this->redirect('opt/index', ['id'=>$user_id]);

                 }

            }

               

       return $this->render('user', [

         'model' => $model,

       ]);

    }




Now this opt/index page has 2 parameter to choose (Model as below):




class PrefForm extends ActiveRecord

{

    public $user_id;

    public $var1;

    public $var2;

    

    public static function tableName()

    {

        return '{{%opt%}}';

    }

    

    public function rules()

    {

        return [

           	  ['user_id','required'],//this value is getting redirected from the user reg page. This will be hidden input for this index page. 

                  ['var1','required'],

                  ['var2','required'],

               ];  

    }


    public function attributeLabels()

    {

        return [

		  'user_id'=> 'User Id',

                  'var1' => 'Variable1',

                  'var2' => 'Vaiable2',

               ];

    }

    

   public function opts()

    {

        if ($this->validate()) 

        {

        $pref = new PrefForm();

        $pref->var1 = $this->var1;

        $pref->var2 = $this->var2;

        

         if ($pref->save()) {

            return $pref;

           }

        }

       return null;

     }   

}



Index Controller:




public function actionIndex()

   

    {

        $model = new PrefForm();

        if ($model->load(Yii::$app->request->post())) {

		if ($pref = $model->opts())

                   return $this->redirect(['resources/resource']);

                   }

            }

            

        return $this->render('index', [

           'model' => $model,

        ]);

    }




I want to save the "$user_id" in the "opt" table.

Please show us the schemas of the involved tables: I’m not sure, but probably ‘user’ table for user registration and ‘opt’ table for user preferences.

Thank you for your reply.

Simply created two tables:

No indexing and primary-foreign key relationship is done.

The code below redirects to controller OptController and action actionIndex. So I will assume you are asking on how to display user and the preferences.


if ($user = $model->signup())  

{

   return $this->redirect('opt/index', ['id'=>$user_id]);

}



Then in that controller you do something like this:




//controller

class OptController extends \yii\web\Controller

{

	public function actionIndex($user_id)

	{

		$user = User::findOne($user_id); //User is the user model probably in app\models

		if(empty($user))

		{

			// user not found, Throw an exception

		}

		

		$opts = Opt::find()->where(['user_id'=>$user_id])->all();

		

		return $this->render('index', [

			'user'=>$user,

			'options'=>$opts

		]);

	}

}




//index.php in views/opt


User ID:<?= $user->user_id ?>


<h3>Preferences</h3>

<ul>

	<?php foreach($options as $option): ?>

		<li>Var1:<?= $option->var1 ?>, Var2: <?= $option->var2 ?></li>

	<?php endforeach; ?>

</ul>

HTH

Thanks for your ideas.

I shall try to reproduce scenario as guided by you. I shall post it with the results.

Regards,

Sid

Thanks experts.

I have tried the you guided me. I reproduce the scenario. But i am getting error like "Bad Request (#400), Bad Request (#400)). Missing required parameters: id". May be I am missing something.

But in DB user information is getting saved.

Can you just guide me what I am missing??

Controller:




public function actionUser()

{

     $model = new userForm();

        if ($model->load(Yii::$app->request->post())) {

            if ($user = $model->signup())  {

                        return $this->redirect(['index','id'=>$id]);

                      }

            }

            

       return $this->render('user', [

         'model' => $model,

       ]);

    }


     public function actionIndex($id)

   

    {

                    $user=UserForm::findOne($id);

                     

                      

                      return $this->render('index',[

                        'user'=> $user

                      ]);

    }



I have tried below code also:




ublic function actionUser()

   

    {

     $model = new userForm();

        if ($model->load(Yii::$app->request->post())) {

            if ($user = $model->signup())  {

                        return $this->redirect(['index','id'=>$model->id]);

                      }

            }

            

          

       return $this->render('user', [

         'model' => $model,

       ]);

    }


     public function actionIndex($id)

   

    {

                    $id=\Yii::$app->user->identity->id;

                     

                      

                      return $this->render('index',[

                        'model'=> $this->findModel($id),

                      ]);          

    }



Index.php:




User Id: <?= $user->id ?>

Regards,

Sid

You’ll have to put full stack trace or show us the URL you are trying to access. Message is clear that you’re not passing the mandatory id query param

Hello Experts,

Thank you all for sharing your ideas regarding this topic.

I have tried with a test scenario to resolve this issue and perhaps got the point where I was doing wrong.

I was mixing up the nomenclatures of the models and parameters.

Regards,

Sid

Great that you resolved it.

Cheers