错误的请求(#400)-缺少必需的参数:YII2中的id
我想使用GII工具进行CRUD操作,但当我试图保存帖子时,收到错误消息错误的请求(#400)-缺少必需的参数:YII2中的id,yii2,yii2-advanced-app,Yii2,Yii2 Advanced App,我想使用GII工具进行CRUD操作,但当我试图保存帖子时,收到错误消息缺少必需的参数:id 邮政总监: public function actionCreate() { $model = new Post(); if ($model->load(Yii::$app->request->post())) { $model->post_create_time=date('Y-m-d h:m:s'); $model->sa
缺少必需的参数:id
邮政总监:
public function actionCreate()
{
$model = new Post();
if ($model->load(Yii::$app->request->post())) {
$model->post_create_time=date('Y-m-d h:m:s');
$model->save();
return $this->redirect(['view', 'id' => $model->id_post]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
为什么总是出现这种错误?您可以在这里尝试以下几点:
- 使用前检查
是否为空$model->post_id
$success=$model->save();
// if it's false, it means there was an error
var_dump($success);
exit;
- 在使用前检查
是否成功:save()
if($model->save()){
return $this->redirect(['view', 'id' => $model->id_post]);
}else{
// show errors
var_dump($model->getErrors();
exit;
}
除此之外,我建议您发布actionView
和classpost
的代码
public function actionCreate()
{
$model = new Post();
if ($model->load(Yii::$app->request->post())) {
$model->post_create_time=date('Y-m-d h:m:s');
$model->save(false);
return $this->redirect(['view', 'id' => $model->id_post]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
确保您执行了$model->save(false)
并查看它是否有效。试试这个
public function actionCreate()
{
$model = new Post();
if ($model->load(Yii::$app->request->post())) {
$model->post_create_time=date('Y-m-d 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,
]);
}
}
这显然发生在$this->redirect上。检查main.php文件中的url规则。 它应该位于main.php中的某个位置
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
...
]
],
某些字段太短,因此无法存储,但现在会显示准确的错误消息。
我增加了字段大小,没关系。显示
actionView()
@arogachev的代码这是actionView
:public function actionView($id){return$this->render('view',['model'=>$this->findModel($id),]);}
我检查了save()
,结果是array(0){
。接下来呢?我仍然明白我应该做什么后,我检查它。我是yii的新手。actionView
:public function actionView($id){return$this->render('view',['model'=>$this->findModel($id),]);}
我已经编辑了代码:你需要将save()
方法属性化为一个变量(我把它命名为$success
)然后转储该变量以查看保存是否有效。我尝试过,结果是bool(false)
thank you@Abhimanyu,这是工作:),但我不知道为什么。你能解释一下为什么$model->save(false)
。为什么要false
?@Shinoda_u当您使用$model->save(false)
时,它会跳过验证。如果这对您有效,则表示您在模型中提到的规则
不正确。修复您的规则
并尝试在不使用false的情况下保存您的模型。如果一切都是正确的,它就会工作。