In Yii2 after adding data to clear the form and display a flash message on the same page without re-sending?

public function actionAdd()
{
 $model = new News();

 if ($model->load(Yii::$app->request->post())) {
 if ($model->save()) {
 Yii::$app->session->setFlash('success', 'Luck: News added!');
 $model = new News();
 } else {
 Yii::$app->session->setFlash('error', 'Error: failed to add news!');
}
}

 return $this->render('add', compact('model'));
}


And that's such a horror when you refresh the page:
5e0ec23330848537983155.png
April 4th 20 at 00:37
2 answers
April 4th 20 at 00:39
Solution
Need to do a redirect after saving to throw off the post. And the session will be a flash message.
April 4th 20 at 00:41
Solution
If you don't need to do a redirect to another page — you can reload the page using $this->refresh(). The page is reloaded, the form is cleared, the flash message will be displayed. Then you can re-fill the form with new data.

From your code will be lost the extra lines:

public function actionAdd()
{
 $model = new News();

 if ($model->load(Yii::$app->request->post()) && $model->save()) {
 Yii::$app->session->setFlash('success', 'Luck: News added!');
 return $this->refresh();
 } else {
 Yii::$app->session->setFlash('error', 'Error: failed to add news!');
}

 return $this->render('add', compact('model'));
}

Find more questions by tags Yii