cakePHP1.3使ってます。
formヘルパーは便利です。何でもAjaxでやりたいのであれば便利さは限定されるのかもしれませんが、それでもエラーがある場合のチェック機能などを使うとそれはそれで便利に使えるのかもしれません。今回はform登録をAjax機能を使わずに実施する想定で、Userテーブルに名前と生年月日と性別を登録する超シンプルな構成を想定します。formヘルパー自体今までほとんど無視していましたので、便利な機能を覚えるためにメモります。
テーブル - users
フィールド | 種別 | 照合順序 | NULL | デフォルト値 | その他 |
id | int(11) | いいえ | None | auto_increment | |
name | varchar(30) | utf8_unicode_ci | いいえ | None | |
birth | date | はい | NULL | ||
gender | varchar(2) | utf8_unicode_ci | はい | NULL |
モデル - user.php
<?php class User extends appModel{ var $name = 'User'; public $validate = array( 'name' => array( 'rule' => 'notEmpty', 'message' => 'nameは必ず入力してください'), 'birth' => 'date', 'gender' => array( 'rule' => array('inList', array('男性','女性')), 'message' => '「男性」か「女性」を入力してください。') ); } ?>
コントローラー - formtests_controller.php
<?php class FormtestsController extends AppController{ public $name = 'Formtests'; public $uses = array('User'); public $layout = 'formtests'; function index(){ if(!empty($this->data)){ if($this->User->save($this->data)){ $this->redirect('./'); } } } } ?>
ビュー - index.cpt
<h1>Form Test</h1> <?php echo $form->create('Formtest',array('action'=>'index')); ?> <?php echo $form->input('User.name',array('label'=>'名前')); ?> <?php echo $form->input('User.birth',array('label'=>'生年月日','dateFormat'=>'YMD','minYear'=>date('Y')-80,'maxYear'=>date('Y'),'separator'=>'/','monthNames'=>false)); ?> <?php echo $form->input('User.gender',array('label'=>'性別','options'=>array('男性'=>'男性','女性'=>'女性'))); ?> <?php echo $form->submit('add'); ?> <?php echo $form->end(); ?>
css
body{ background-color:#999; font-family:'Trebuchet MS', Trebuchet, sans-serif; font-size:12px; margin:10px; } h1{ font-size:30px; } .error-message{ color:#f00; } label{ display:block; width:70px; float:left; }