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

时间:2017-08-28 01:33:38

标签: php yii2

我的控制器

public function actionCreate()

{
    $model = new SuratMasuk(['scenario' => 'create']);

    if ($model->load(Yii::$app->request->post()))
    {
        try
        {
           $picture = UploadedFile::getInstance($model, 'imageFile');
           $model->imageFile = $_POST['SuratMasuk']['id_suratmasuk'].'.'.$picture->extension;

           if($model->save())
           {

               $picture->saveAs('uploads/' . $model->id_suratmasuk.'.'.$picture->extension);
               Yii::$app->getSession()->setFlash('success','Data saved!');
               return $this->redirect(['view','id'=>$model->id_suratmasuk]);
           }
           else
           {
               Yii::$app->getSession()->setFlash('error','Data not saved!');
               return $this->render('create', [
                     'model' => $model,
               ]);
           }
       }
       catch(Exception $e)
       {
          Yii::$app->getSession()->setFlash('error',"{$e->getMessage()}");
      }
    }
    else
    {
        return $this->render('create', [
            'model' => $model,
        ]);
    }

}

当我尝试保存我的帖子时收到此错误消息。它只是上传文本而不是图像。我试过$ model-> save(false);但没有工作

我是yii的新手,我很感激你的帮助

1 个答案:

答案 0 :(得分:0)

我想这是因为你试图在这里传递id

return $this->redirect(['view', 'id' => $model->id_suratmasuk]);

并且由于actionView几乎肯定需要id作为参数,因此$model->id_suratmasuk为空,会出现此错误。

  • 您需要在rules()模型中设置正确的SuratMasuk
  • 不要直接使用POST变量,这是要求被黑客入侵。
  • 如果您需要保存来自用户的任何内容,请不要使用save(false)(必须进行验证!)。
  • 为所有属性添加rules(),这样就不会出现此id_suratmasuk为空的意外情况。
  • 检查saveAs()个实例上UploadedFile的结果 - 这也可以false
相关问题