Yii 设置 flash消息 创建一个渐隐形式的消息框

时间:2022-10-22 16:19:07
 /*适用情况:比如提交一个表单,提交完成之后在页面展示一条提示消息。
控制器里面这样写:
单条消息:
*/
\Yii::$app->getSession()->setFlash('error', 'This is the message'); \Yii::$app->getSession()->setFlash('success', 'This is the message'); \Yii::$app->getSession()->setFlash('info', 'This is the message');
#多条消息:
\Yii::$app->getSession()->setFlash('error', ['Error 1', 'Error 2']); #然后是视图里面: 先引入Alert:use yii\bootstrap\Alert;
if( Yii::$app->getSession()->hasFlash('success') ) {
echo Alert::widget([
'options' => [
'class' => 'alert-success', //这里是提示框的class
],
'body' => Yii::$app->getSession()->getFlash('success'), //消息体
]);
}
if( Yii::$app->getSession()->hasFlash('error') ) {
echo Alert::widget([
'options' => [
'class' => 'alert-error',
],
'body' => Yii::$app->getSession()->getFlash('error'),
]);
}

项目代码示例:

 //c控制器里面这样写 CompanyInfoController
//公司信息
public function actionIndex()
{
$result = CompanyService::CompanyInfo();
$types = Yii::$app->params['companyType'];
$model = CompanyInfo::find()->where(['id' =>Yii::$app->company->getId()])->one(); if (Yii::$app->request->post() && CompanyService::UpdateConpanyInfo(Yii::$app->request->post())) {
Yii::$app->session->setFlash('flag', 'success'); return $this->redirect('/system/company-info/index');
}
return $this->render('index', [
'staffNum' => $result['staffNum'],
'model' => $model,
'type' => $types,
'businessList' => $result['businessList'],
'businessParentId' => $result['businessParentId'],
'sonBusInessList' => $result['sonBusInessList']
]);
} //视图里面 index.php
<script type="text/javascript">
//消息提示start
<?php $flag = Yii::$app->session->getFlash('flag');if($flag == 'success'): ?> layer.msg('公司信息更新成功'); <?php endif; ?>
//消息提示end </script>