CakePHP1.3.6:入力値に合致するテーブルのデータを一覧表示する。
今回は、前回の画面によくある絞り込み機能を追加する。
以下のように画面に入力フィールドを設け、それに合致するデータを一覧で表示する。
Formヘルパーを使うことで、入力後に送信しても入力フィールドがクリアされない。これは便利。
モデル
モデルは先のログと同じ。
コントローラーの作成
customer_controller.phpを以下のように変更する。
<?php class CustomersController extends AppController{ public $name = 'Customers'; public $layout = 'myznala'; function index(){ $this->set('title_for_layout', "モデルのテスト"); $req=null; if(!empty($this->data)){ require_once '../vendors/MyConverter.class.php'; $req = MyConverter::getRequestParams($this->data["Customer"]); $result = $this->Customer->find('all', array('conditions' => array('Customer.name like ?' => array("%{$req["name"]}%")))); }else{ $result = $this->Customer->find('all'); } $this->set('result',$result); } } ?>
ビューの作成
index.ctpを以下のように変更する。上部に入力フィールドをFormヘルパーで作成する。
<?php echo $form->create(null,array('type'=>'post','action'=>'.')); echo $form->input('Customer.name', array('type' => 'text', 'size' => 10)); echo $form->end('送信'); ?> <table> <tr> <th>ID</th> <th>名前</th> <th>郵便番号</th> <th>住所</th> <th>電話</th> <th>携帯</th> <th>メール</th> <th>更新日</th> </tr> <?php foreach ($result as $arr){ echo '<tr>'; echo "<td>{$arr['Customer']['id']}</td>"; echo "<td>{$arr['Customer']['name']}</td>"; echo "<td>{$arr['Customer']['zip']}</td>"; echo "<td>{$arr['Customer']['address']}</td>"; echo "<td>{$arr['Customer']['tel']}</td>"; echo "<td>{$arr['Customer']['mobile']}</td>"; echo "<td>{$arr['Customer']['mail']}</td>"; echo "<td>{$arr['Customer']['timestamp']}</td>"; echo '</tr>'; } ?> </table>
CSSの修正
CakePHPのデフォルトのCSS(/app/webroot/css/cake.generic.css)だと、
- inputフィールドの幅が98%に設定されている
- inputフィールドで改行される。
- checkbox,radioのラベルの位置がずれる
ので、これを修正する。
/* input, textarea { clear: both; font-size: 140%; font-family: "frutiger linotype", "lucida grande", "verdana", sans-serif; padding: 1%; width:98%; } */ input, textarea { /* clear: both;*/ padding: 1%; } select { /* clear: both;*/ font-size: 120%; vertical-align: text-bottom; } select[multiple=multiple] { width: 100%; } option { font-size: 120%; padding: 0 3px; } input[type=checkbox] { /* clear: left; float: left;*/ margin: 0px 6px 7px 2px; width: auto; } div.checkbox label { display: inline; } input[type=radio] { /* float:left;*/ width:auto; margin: 0 3px 7px 0; }