0

I try to save current user_id to the education table in database. However,the data of user_id is not filled. This is my code.

At model

public function rules()
{
    return [
        [['year', 'fieldstudy', 'institute', 'grade'], 'required'],
        [['user_id'], 'integer'],
        [['year', 'fieldstudy', 'institute', 'grade'], 'string', 'max' => 255],
    ];
}


public function attributeLabels()
{
    return [
        'education_id' => 'Education ID',
        'user_id' => 'User ID',
        'year' => 'Year',
        'fieldstudy' => 'Fieldstudy',
        'institute' => 'Institute',
        'grade' => 'Grade',
    ];
}

public function getUser()
{
    return $this->hasOne(User::className(), ['user_id' => 'user_id']);
}      

At controller

     public function actionCreate()
{
    $model = new Education();
    $model->user_id =Yii::$app->user->id;

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

        return $this->redirect(['view', 'id' => $model->education_id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

How can I solve my problem and fix my code? Thanks

Fyp16
  • 131
  • 1
  • 5
  • 16

2 Answers2

0

update Yii::$app->user->id to Yii::$app->user->identity->id.

public function actionCreate()
    {
        $model = new Education();

        if ($model->load(Yii::$app->request->post())) {
        $model->user_id =Yii::$app->user->identity->id;
        if($model->save()){
            return $this->redirect(['view', 'id' => $model->education_id]);
        } 
        }
            return $this->render('create', [
                'model' => $model,
            ]);
    }
jithin
  • 920
  • 9
  • 17
0

You have to check two things

  1. Check whether the user is logged in.
  2. Use Yii2 debugger to see whether we are getting the id value of the logged in user by the code Yii::$app->user->id or Yii::$app->user->id

Use Yii2 debugger to check whether the correct user id value we are getting by using the code

Yii::info("User id=".Yii::$app->user->id); 

Full code you have to try in the controller is given below

 public function actionCreate() {
        $model = new Education();

        //checking whether we are getting the logged in user id value
        Yii::info("User id=".Yii::$app->user->id); 

        $model->user_id = Yii::$app->user->id;

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

             //checking here the saved user id value in  table
             Yii::info("checking User id after saving model=".$model->user_id); 

            return $this->redirect(['view', 'id' => $model->education_id]);
        } else {
            return $this->render('create', [
                        'model' => $model,
            ]);
        }
    }

Now after running the application you can check using Yii2 debugger the values that are set in the user id in various places.

Ajith
  • 53
  • 1
  • 5