コントローラ:
This file contains 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')); | |
} | |
} |
これはこれでわかりやすく良い流れだとは思いますが、いくつかのビューでこれを使う場合、ビューで、同じようなコードを何度も書くことになります。この「ビューで同じようなコードを何度も書くこと」を避けたいがために、CakePHP 脳の自分はつい部分ビューを作る方に走ってしまうのですが、Yii で Twitter Bootstrap を扱えるエクステンションを触っていたら、それをウィジェットで作ったのがあったので、これはいい!っと思い、シンプルに加工してパクってみました。それが以下
This file contains 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), | |
)); | |
} | |
} | |
} | |
} |
ビューで使う場合は /config/main.php の import 部分に 'application.components.widgets.*' を追加して、/components/widgets 下にFlash.php を置く。あとはビューで <php $this->widget('Flash'); ?> と書けばOKです ($keyの配列の値にないものを使う場合は <php $this->widget('Flash', array('keys' => 'キーの名前')); ?> )。
ウィジェットって...何?から、ウィジェットってこういう使い方もできるんだなぁと少しずつなってきました。
0 件のコメント:
コメントを投稿