Bad request (No. 400) - Lack of required parameters: id in YII2

I want to do a CRUD operation using the GII Tool, but I get the error Missing required parameters: id when I try to save the message.

Mail Controller:

 public function actionCreate() { $model = new Post(); if ($model->load(Yii::$app->request->post())) { $model->post_create_time=date('Ymd h:m:s'); $model->save(); return $this->redirect(['view', 'id' => $model->id_post]); } else { return $this->render('create', [ 'model' => $model, ]); } } 

Why am I always getting this error?

+5
source share
5 answers

Try

 public function actionCreate() { $model = new Post(); if ($model->load(Yii::$app->request->post())) { $model->post_create_time=date('Ymd h:m:s'); $model->save(false); return $this->redirect(['view', 'id' => $model->id_post]); } else { return $this->render('create', [ 'model' => $model, ]); } } 

Make sure you do $model->save(false) and see if it works.

+4
source

A few things you can try here:

  • Check if $model->post_id null before using it.

See an example below.

 $success=$model->save(); // if it false, it means there was an error var_dump($success); exit; 
  • Check if save() successful before using it:

see below code

 if($model->save()){ return $this->redirect(['view', 'id' => $model->id_post]); }else{ // show errors var_dump($model->getErrors(); exit; } 

In addition, I would advise you to publish the code for the actionView and the Post class as well

0
source

try it

 public function actionCreate() { $model = new Post(); if ($model->load(Yii::$app->request->post())) { $model->post_create_time=date('Ymd h:m:s'); if($model->save()) return $this->redirect(['view', 'id' => $model->id_post]); else { return $this->render('create', [ 'model' => $mod`enter code here`el, ]); } } else { return $this->render('create', [ 'model' => $model, ]); } } 
0
source

This obviously happens when redirecting $ this->. Check your URL rules in the main.php file. It should be located somewhere here in main.php

 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'enableStrictParsing' => false, 'rules' => [ ... ] ], 
0
source

Some fields are too short, so they cannot be saved, but now show accurate error messages. I increase the size of the field, this is normal.

0
source

Source: https://habr.com/ru/post/1213873/


All Articles