Last active
October 2, 2015 08:57
-
-
Save jamband/2214506 to your computer and use it in GitHub Desktop.
Yii Framework: Flash message example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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), | |
)); | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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')); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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