Reputation: 449
I am trying to insert data into database for using yii2. It is working well but I having a little problem each time insert it goes into the database and the field becomes empty. But when I refresh it goes back it to the database again. Any time I refresh it adds the same data to the database again and I don't know why.
the is my controller class
public function actionCompose() {
$topic = new Topic();
$topic->load($_POST);
$topic->save();
return $this->render('compose');
}
this is my view class 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(); ?>
Upvotes: 1
Views: 63
Reputation: 449
i modified it i needed to add 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');
}
Upvotes: 0
Reputation: 596
I think you should be check your model before save that is posted or no!
public function actionCompose() {
$topic = new Topic();
if($topic->load(Yii::$app->request->post())) {
$topic->save();
}
return $this->render('compose');
}
Upvotes: 1
Reputation: 5731
You are not checking that request is POST or normal request.
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
]);
}
}
Upvotes: 1
Reputation: 4160
There is problem with your code as:
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');
}
If still occurs provide validation rules in your Post Model
Upvotes: 1