セレクトボックスでグループ分けするならHash::combineが便利
開発環境:CakePHP2.5.1
Hash::combineを使ってセレクトボックスを作る
コントローラー側
1 2 3 4 5 6 7 |
<?php public function index() { $posts = $this->Post->find('all'); $result = Hash::combine($posts, '{n}.Post.id', '{n}.Post.data'); $this->set(compact('result')); } ?> |
ビュー側
1 |
<?php echo $this->Form->input('post', array('options' => $result)); ?> |
これでセレクトボックスを作ることができます。
find(‘list’)を使ってセレクトボックスを作る
上記のような簡単なセレクトボックスであれば、Hash::combineを使わずにfind(‘list’)を使ったほうが簡単です。
1 |
<?php $result = $this->Post->find('list', array('fields'=>array('data'))); ?> |
ビュー側の処理は同じなので、こちらの方がコントローラーがすっきりします。
グループ分けをするならHash::combine
いよいよ本題のセレクトボックス内でのグループ分けです。
この場合はHash::combineを使って次のように行います。
1 2 3 4 |
<?php $posts = $this->Post->find('all'); $result = Hash::combine($posts,'{n}.Post.id','{n}.Post.data','{n}.Post.group'); ?> |
第4引数に指定したデータでグルーピングしてセレクトボックスを作ってくれます。
柴田 篤志
最新記事 by 柴田 篤志 (全て見る)
- WordPressとCakePHPの共存 - 2014年10月22日
- サイトマップの作成方法 - 2014年10月12日
- INSERTしたIDを取得する - 2014年10月4日