CakePHPでBootstrapのアラートを使う-自前でメッセージ機能を作る-
さて、CakePHPの機能でフラッシュメッセージがありますよね。
こんなやつ
これをBootstrapのalertのデザインでやりたい!
でもCSSいじるのめんどくさいし(苦手なだけ(ーヘー;))、自前でフラッシュメッセージの機能を作ってみました!
とりあえず、infoとdangerの2種類分です!
使いたい時にコントローラ内でセッションに登録すると呼び出されます。
public function test(){ $this->Session->write('infoMes','いいね!');//infoのalertを呼び出し $this->Session->write('errorMes','よくない!');//dangerのalertを呼び出し return; }
実装は以下の通りです。
AppController
public function beforeRender(){ //メッセージがあればViewに渡す if($this->Session->check('infoMes')){ $mes = $this->Session->read('infoMes'); $this->set('infoMes',$mes); $this->Session->delete('infoMes');//表示は1度なので、セッションは削除 } if($this->Session->check('errorMes')){ $mes = $this->Session->read('errorMes'); $this->set('errorMes',$mes); $this->Session->delete('errorMes'); } }
default.ctp
<!-- メッセージの表示 --> <?php if(isset($infoMes)){ ?> <div class="row"> <div class="col-xs-12 text-center alert alert-info" role="alert"><?php echo $infoMes; ?></div> </div> <?php } if(isset($errorMes)){ ?> <div class="row"> <div class="col-xs-12 text-center alert alert-danger" role="alert"><?php echo $errorMes; ?></div> </div> <?php } ?>