YII2 - Save user ID to work with it on other pages

145 Views Asked by At

I'm building a questionnaire site.
On this site the user enters his email to receive the result of his questionnaire. So this site has no authentication.

How do I store the user's email to the end of the questionnaire?

It is my User model:

<?php

namespace common\models;

use Yii;
use \yii\db\ActiveRecord;
// use yii\web\IdentityInterface;

/**
 * This is the model class for table "user".
 *
 * @property int $id
 * @property string $email
 * @property string $name
 * @property string $family
 * @property string $major
 * @property string $univercity
 * @property int $education
 * @property int $gender
 * @property int $age
 * @property int $income
 * @property int $get_result
 * @property int $created_at
 */
class User extends ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            // TimestampBehavior::className(),
        ];
    }


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['email', 'created_at'], 'required'],
            [['education', 'gender', 'age', 'income', 'get_result', 'created_at'], 'integer'],
            [['email', 'name', 'family', 'major', 'univercity'], 'string', 'max' => 255],
            [['email'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'email' => 'Email',
            'name' => 'Name',
            'family' => 'Family',
            'major' => 'Major',
            'univercity' => 'Univercity',
            'education' => 'Education',
            'gender' => 'Gender',
            'age' => 'Age',
            'income' => 'Income',
            'get_result' => 'Get Result',
            'created_at' => 'Created At',
        ];
    }
}

1

There are 1 best solutions below

3
Bizley On

There are many ways of achieving that, it mostly depends on your logic under the hood.

One of the easiest is to use session.

First store the email in session:

\Yii::$app->session->set('questionnaire-email', $usersEmail);

Then, when you want to use it:

$email = \Yii::$app->session->get('questionnaire-email');