Class common\widgets\Alert

Inheritancecommon\widgets\Alert » yii\bootstrap5\Widget
Source Code https://github.com/yiisoft/yii2-app-advanced/blob/master/common/widgets/Alert.php

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:

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:

Yii::$app->session->setFlash('error', ['Error 1', 'Error 2']);

Public Properties

Hide inherited properties

Property Type Description Defined By
$alertTypes array The alert types configuration for the flash messages. common\widgets\Alert
$closeButton array The options for rendering the close button tag. common\widgets\Alert

Public Methods

Hide inherited methods

Method Description Defined By
run() common\widgets\Alert

Property Details

Hide inherited properties

$alertTypes public property

The alert types configuration for the flash messages. This array is setup as $key => $value, where:

  • key: the name of the session flash variable
  • value: the bootstrap alert type (i.e. danger, success, info, warning)
public array $alertTypes = [
    
'error' => 'alert-danger',
    
'danger' => 'alert-danger',
    
'success' => 'alert-success',
    
'info' => 'alert-info',
    
'warning' => 'alert-warning',
]
$closeButton public property

The options for rendering the close button tag. Array will be passed to \yii\bootstrap\Alert::closeButton.

public array $closeButton = []

Method Details

Hide inherited methods

run() public method

public void run ( )

                public function run()
{
    $session = Yii::$app->session;
    $flashes = $session->getAllFlashes();
    $appendClass = isset($this->options['class']) ? ' ' . $this->options['class'] : '';
    foreach ($flashes as $type => $flash) {
        if (!isset($this->alertTypes[$type])) {
            continue;
        }
        foreach ((array) $flash as $i => $message) {
            echo \yii\bootstrap5\Alert::widget([
                'body' => $message,
                'closeButton' => $this->closeButton,
                'options' => array_merge($this->options, [
                    'id' => $this->getId() . '-' . $type . '-' . $i,
                    'class' => $this->alertTypes[$type] . $appendClass,
                ]),
            ]);
        }
        $session->removeFlash($type);
    }
}