我正在尝试将数据插入数据库以使用yii2。 它运作良好但我每次都有一点问题 插入它进入数据库,该字段变空。 但是当我刷新它再次回到数据库。 每次刷新它都会再次向数据库添加相同的数据,我不知道为什么。
是我的控制器类
public function actionCompose() {
$topic = new Topic();
$topic->load($_POST);
$topic->save();
return $this->render('compose');
}
这是我的视图类compose.php
<?php $form = ActiveForm::begin(); ?>
<input type="name" class="form-control" required="true" name="Topic[topic]" id="topic" placeholder="topic">
<textarea type="name" cols="30" rows="10" class="form-control" required="true" name="Topic[about]" id="" placeholder="about"></textarea>
<input type="name" class="form-control" required="true" name="Topic[category]" id="category" placeholder="category">
<?= Html::submitButton('Save', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
<?php ActiveForm::end(); ?>
答案 0 :(得分:1)
您的代码存在以下问题:
public function actionCompose()
{
$topic= new Topic();
//assuming post() request
if($topic->load(Yii::$app->request->post()) && $topic->validate()){
//save() must be after validate()
$topic->save();
}
return $this->render('compose');
}
如果仍然发生,请在您的帖子模型中提供验证规则
答案 1 :(得分:1)
我认为你应该在保存发布之前检查你的模型,否则不要!
public function actionCompose() {
$topic = new Topic();
if($topic->load(Yii::$app->request->post())) {
$topic->save();
}
return $this->render('compose');
}
答案 2 :(得分:1)
您没有检查该请求是POST还是正常请求。
public function actionCompose()
{
$topic= new Topic();
// POST request
if ($topic->load(Yii::$app->request->post()))
{
$topic->load($_POST);
$topic->save();
return $this->redirect(['index']); // change name as yours
}
else // Not a form submission
{
return $this->render('compose', [
'model' => $topic, // change name as yours
]);
}
}
答案 3 :(得分:0)
我修改了它我需要添加return return $this->refresh();
public function actionCompose()
{
$topic= new Topic();
if ($topic->load(Yii::$app->request->post()) && $topic->validate()) {
$topic->load($_POST);
$topic->save();
return $this->refresh();
}
return $this->render('compose');
}