Yii2 第11章 页面提示消息 Yii2 第11章 页面提示消息

2022-06-27

一、适用情况

比如提交一个表单,提交完成之后在页面展示一条提示消息。

二、实现方法

①、控制器

单条消息:

\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']);

②、视图

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'),
    ]);
}

如果有消息就会显示对应消息,表现是一个div,和 bootstrap 的警告框是一样的。

你想把消息提示放在哪里,把上述代码就放到那里就可以了。

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开微信扫一扫,即可进行扫码打赏哦

阅读 554