Saurabh Saurabh - 2 months ago 84
PHP Question

Yii2 : Bad Request (#400) Missing required parameters: id

My controller :

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

if ($model->load(Yii::$app->request->post()))
{
$imageName = $model->primary_name;
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension);
$model->id_image = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();

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

}


Getting this error on submitting my form, dont know what's wrong with it..
Tried with
$model->save(false);
..but not working as well

Answer

Try with getPrimaryKey() method:

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

            if ($model->load(Yii::$app->request->post())) 
            {
                $imageName = $model->primary_name;
                $model->file = UploadedFile::getInstance($model, 'file');
                $model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension);
                $model->id_image = 'uploads/'.$imageName.'.'.$model->file->extension;
                if($model->save())
                {

                   $lastInsertID = $model->getPrimaryKey();
                   return $this->redirect(['view', 'id' => $lastInsertID]);
                }
               else
               {
                   // print_r($model->getErrors()); => check whether any validation errors are there
               }


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

    }
Comments