我想设置 Flash 消息,但如果添加重定向,Flash 消息就会丢失。如果我删除重定向代码行,则会显示闪存消息,但如果我在单击 F5 刷新时删除重定向,它将再次运行文件提交。 如何使重定向与 Flash 消息一起工作?
我的控制器的流程是这样的:
public function actionImportVehiclecsv()
{
$model = new CrmImportVehicle();
$session = Yii::$app->session; // Get the session component
if (Yii::$app->request->isPost) {
$model->csvVehicleFile = UploadedFile::getInstance($model, 'csvVehicleFile');
$model->csvAccount = Yii::$app->request->post('CrmImportVehicle')['csvAccount'];
if ($model->csvVehicleFile) {
if ($filePath = $model->upload()) {
$processResult = $model->processVehicleFile($filePath);
if ($processResult === true) {
$session->setFlash('success', 'CSV file uploaded and data inserted successfully.');
} elseif ($processResult === false) {
$session->setFlash('error', 'Error in CSV row: Vehicle No or Username cannot be blank');
} else {
$session->setFlash('error', $processResult); // Set error flash message for other errors
}
$session->set('processed', true); // Indicate that the form was processed
} else {
$session->setFlash('error', 'Error uploading CSV file.');
}
} else {
$session->setFlash('error', 'No file was uploaded.');
}
return $this->refresh(); // if i remove this line, the flash message works.
} elseif ($session->get('processed')) {
$session->remove('processed'); // Clear the 'processed' flag for GET requests
return $this->refresh(); // Refresh the page if it was previously processed
}
// Render the view for GET requests
return $this->render('import-vehiclecsv', ['model' => $model]);
}
Flash消息的概念是这样的:该消息仅针对一次请求而存在,然后被删除。
我建议您使用“removeAfterAccess”参数检查刷新后是否可以保留消息。
在 Yii 文档中 [https://www.yiiframework.com/doc/api/2.0/yii-web-session#addFlash()-detail][1]
$this->refresh()
不执行任何额外的服务器端逻辑。尝试使用类似 $this->redirect(Yii::$app->request->referrer)
的东西