edo1z blog

プログラミングなどに関するブログです

cakePHP Transitionコンポーネント

便利らしい。調べよう。fileBinderの例文で使われているので調べた。多分これだろう。

24時間cakePHP Transitionコンポーネント1.0

24時間cakePHPといのはいい名前だな。

↓TransitionComponentの紹介記事 TransitionComponent for CakePHPで簡単確認画面実装

Transition Componentは、セッションと、主にCakePHPのモデルバリデーションの機能を利用してページ遷移を管理しており、 使いこなすとページ遷移管理を非常にすっきりとしたコードで実現することができます。

これはフォーム入力→確認画面→完了画面みたいなやつをすっきりと書けるということだなー!いいねえ。

追記:cakePHP2.3でTransitionコンポーネントを使ってみる

使ってみたらかなり便利だった。まだ初歩的な使い方しかしてないけど。 特にモデルに特別なことを追記するような必要はない。 コントローラーでTransitionコンポーネントを呼び出して、使えばいいだけ。

コントローラー UsersController.php

class UsersController extends AppController {
    public $components = array('Session', 'Filebinder.Ring','Transition.Transition');

    //ユーザ登録画面
    public function index(){
        $this->Ring->bindUp();
        $this->Transition->checkData('confirm');
    }

    //確認画面
    public function confirm(){
        $this->Transition->automate('index','save','User');
        $this->set('data', $this->Transition->allData());
    }

    //登録完了画面
    public function save(){
        $this->Transition->checkPrev(array('index','confirm'));
        if($this->User->saveAll($this->Transition->mergedData())){
            $this->Transition->clearData();
        }else{
            $this->Session->setFlash('登録できませんでした。恐れ入りますが再度お試しください。');
            $this->redirect(array('action' => 'index'));
        }
    }
}

ビュー(ユーザー登録画面の最初の画面)index.ctp

<h2>ユーザー登録</h2>

<div class="posts form">
<?php echo $this->Form->create('User', array('action'=>'index','type' => 'file'));?>
<?php echo $this->Form->input('username');?>
<?php echo $this->Form->input('photo', array('type' => 'file'));?>
<?php echo $this->Form->submit('Submit');?>
<?php echo $this->Form->end();?>
</div>

ビュー(登録内容確認画面) confirm.ctp

<h2>確認画面</h2>

<?php $u = $data['users']['index']['User']?>

<table>
<tr>
    <td>名前</td>
    <td><?php echo h($u['username'])?></td>
</tr>
<tr>
    <td>ファイル</td>
    <td><?php echo $u['photo'] ? '添付あり' : '添付なし'?></td>
</tr>
</table>

<?php echo $this->Form->create('User',array('action'=>'confirm'));?>
<?php echo $this->Form->hidden('dummy');?>
<?php echo $this->Form->end('登録');?>

ビュー(登録完了画面) save.ctp

<h2>無料登録</h2>
<p>登録が完了しました。ありがとうございました!</p>

参考: [PHP][CakePHP] とっても便利なTransitionコンポーネント hiromi2424 / TransitionComponent