错误请求(#400)缺少必需参数:yii2中的id

时间:2016-09-30 05:41:23

标签: php yii2

每当我尝试创建一个事件时,点击后创建它就会显示:

  

错误请求(#400)缺少必需参数:id

我曾尝试过$model->save(false);,但当我这样做时,它只会上传文字,而不是图片。

我的eventController代码是:

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

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

            // get the instance of the uploaded file 
            $imageUpload = $model ->event_name;
            $model->file =UploadedFIle::getInstance($model,'file'); 
            if($model->file) {
        $model->event_image='images/'.$imageUpload.'.'.$model->file->extension;
            $model->save();
        $model->file->saveAs( 'images/'.$imageUpload.'.'.$model->file->extension );
} else {
    $model->save();
}




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

1 个答案:

答案 0 :(得分:1)

似乎'id' => $model->event_id正在寻找lastInsertID

试试这个

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

您也可以尝试在模型规则中将字段设为safe

[['field1','field2','field3'], 'safe'],

最后,您可以尝试在$model->load(Yii::$app->request->post())之后检查,如果模型是否设置了属性 print_r($model->attributes);之前的save(false)