yii2-netdisk/widgets/Alert.php

77 lines
2.3 KiB
PHP
Raw Normal View History

2017-08-08 13:02:19 +03:00
<?php
2021-05-19 14:01:06 +02:00
2017-08-08 13:02:19 +03:00
namespace app\widgets;
use Yii;
/**
* Alert widget renders a message from session flash. All flash messages are displayed
* in the sequence they were assigned using setFlash. You can set message as following:
*
* ```php
* Yii::$app->session->setFlash('error', 'This is the message');
* Yii::$app->session->setFlash('success', 'This is the message');
* Yii::$app->session->setFlash('info', 'This is the message');
* ```
*
* Multiple messages could be set as follows:
*
* ```php
* Yii::$app->session->setFlash('error', ['Error 1', 'Error 2']);
* ```
*
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @author Alexander Makarov <sam@rmcreative.ru>
*/
2021-05-19 14:01:06 +02:00
class Alert extends \yii\bootstrap4\Widget
2017-08-08 13:02:19 +03:00
{
/**
* @var array the alert types configuration for the flash messages.
* This array is setup as $key => $value, where:
2017-08-09 20:58:58 +03:00
* - key: the name of the session flash variable
* - value: the bootstrap alert type (i.e. danger, success, info, warning)
2017-08-08 13:02:19 +03:00
*/
public $alertTypes = [
'error' => 'alert-danger',
'danger' => 'alert-danger',
'success' => 'alert-success',
'info' => 'alert-info',
'warning' => 'alert-warning'
];
/**
* @var array the options for rendering the close button tag.
2017-08-09 20:58:58 +03:00
* Array will be passed to [[\yii\bootstrap\Alert::closeButton]].
2017-08-08 13:02:19 +03:00
*/
public $closeButton = [];
2017-11-03 01:38:39 +03:00
2017-08-09 20:58:58 +03:00
/**
* {@inheritdoc}
*/
public function run()
2017-08-08 13:02:19 +03:00
{
$session = Yii::$app->session;
$flashes = $session->getAllFlashes();
2017-08-09 20:58:58 +03:00
$appendClass = isset($this->options['class']) ? ' ' . $this->options['class'] : '';
2017-08-08 13:02:19 +03:00
2017-08-09 20:58:58 +03:00
foreach ($flashes as $type => $flash) {
if (!isset($this->alertTypes[$type])) {
continue;
}
2017-08-08 13:02:19 +03:00
2017-08-09 20:58:58 +03:00
foreach ((array) $flash as $i => $message) {
2021-05-19 14:01:06 +02:00
echo \yii\bootstrap4\Alert::widget([
2017-08-09 20:58:58 +03:00
'body' => $message,
'closeButton' => $this->closeButton,
'options' => array_merge($this->options, [
'id' => $this->getId() . '-' . $type . '-' . $i,
'class' => $this->alertTypes[$type] . $appendClass,
]),
]);
2017-08-08 13:02:19 +03:00
}
2017-08-09 20:58:58 +03:00
$session->removeFlash($type);
2017-08-08 13:02:19 +03:00
}
}
}