Skip to content

Instantly share code, notes, and snippets.

@jamband
Last active October 2, 2015 08:57
Show Gist options
  • Save jamband/2214506 to your computer and use it in GitHub Desktop.
Save jamband/2214506 to your computer and use it in GitHub Desktop.
Yii Framework: Flash message example.
<?php
class Flash extends CWidget
{
public $keys = array(
'success',
'info',
'warning',
'error',
);
public $template = '<div class="flash-{key}">{message}</div>';
/**
* @see CWidget::run()
*/
public function run()
{
if (is_string($this->keys)) {
$this->keys = array($this->keys);
}
foreach ($this->keys as $key) {
if (Yii::app()->getUser()->hasFlash($key)) {
echo strtr($this->template, array(
'{key}' => $key,
'{message}' => Yii::app()->getUser()->getFlash($key),
));
}
}
}
}
<?php
class HogeController class extends Controller
{
...
public function actionCreate()
{
$model = new Hoge();
if (isset($_POST['Hoge'])) {
$model->attributes = $_POST['Hoge'];
if ($model->save()) {
Yii::app()->user->setFlash('success', 'データを保存しました'); // フラッシュメッセージをセット
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('_form', compact('model'));
}
}
<?php if (Yii::app()->user->hasFlash('success')): ?>
<div class="flash-success">
<?php echo CHtml::encode(Yii::app()->user->getFlash('success')); ?>
</div><!-- /.flash-success -->
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment