0

In common\model\LoginForm.php I have declared a variable with the statement:

public $nhs

In rules() I have declared this as boolean & required. This is presented to the user in frontend\views\site\login.php at login as radio buttons which are either true or false.

I need to access the value of this variable set by the user after the user logged in, elsewhere in the process, specifically in:

frontend\views\layouts\main.php

In order to control the options presented to the user. I am relatively new to Yii2 and am struggling to find a solution.

3
  • The variable $nhs is not a field in the database as it can be changed each time the user logs in, so trying to use your suggestion re $_SESSION. So in the Login.php form I use the following code: <?php $radio_ary = [1 => 'NHS',0 => 'Private'] ?> and <?= $form->field($model, 'nhs')->radioList($radio_ary,['unselect' => null]) ?>. I then use $_SESSION['nhs'] = $model->nhs; However I cannot access the value of 'nhs' elsewhere in the application. Have I misunderstood your suggestion? Commented Jun 30, 2019 at 19:41
  • Please add your comment in your question as edit so anyone can see it without searching into the comments Commented Jul 1, 2019 at 6:34
  • @AlanYoung you need to start session everytime to acces the variables with session_start(). So your first do session_start(), then you save the nhs to the session. After, if you want to acces the sessio again you have to open again the session with session_start() Commented Jul 1, 2019 at 12:22

1 Answer 1

1

If you declare the variable in the model, but it is NOT a field in the database, the variable is only temporary, and it will last only till the post action is done and the data is saved. Once you move to another action, and you reload the model the value is gone.

So if you want that info to persist trought all the application you have two options:

  1. Remove the public variable and make that variable a field in your database and store it once the user logs in.
  2. Store it in the user session as $_SESSION['nhs'] = //post variable

If you take the first option, and you store it on the user model that is loged in, you can access that variable everywhere on the app with (If the user is connected ofcourse):

echo Yii::$app->user->identity->nhs;

And if you take the second options you will do:

echo $_SESSION['nhs'];
Sign up to request clarification or add additional context in comments.

1 Comment

Should be noticed, that session variable will be lost too when session closed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.