CakePHP の FormHelper::input の使い方とバリデーションとの関係を勉強します♪ | oki2a24 の続きの投稿となります。
バリデーション、つまり入力チェックの基本を勉強します。
ポイント
- モデルにバリデーション情報を書きます。
- 書き方。
public $validate = array(
‘フィールド名。つまり DB のカラム名‘ => array(
‘rule’ => ‘notEmpty とかルールを記入‘,
‘message’ => ‘エラーメッセージ‘
),
);
前提
- CakePHP 2.1.3 導入済み。
- ドキュメントルート/cake/sample/(ここにCakePHP が入ってます。app ディレクトリとか、.travis.yml ファイルとか。)
ソース
cake/sample/app/Model/Board.php
<?php
class Board extends AppModel {
public $name = 'Board';
public $validate = array(
'name' => array(
'rule' => 'notEmpty',
'message' => '名前を記入してください。'
),
'title' => array(
'rule' => 'notEmpty',
'message' => 'タイトルを記入してください。'
),
'content' => array(
'rule' => 'notEmpty',
'message' => '内容を記入してください。'
),
);
}
?>
フィールドの値として array に設定する rule や message ですが、これだけではありません。ほかにもたくさんのオプションがありますが、それはおいおい見ていきたいです。
cake/sample/app/View/Boards/index.ctp
<h1>送信フォーム・サンプル</h1>
<h2>登録・更新</h2>
<?php
echo $this->Form->create(false, array('type' => 'post', 'action' => 'addRecord'));
echo $this->Form->label('Board.id', 'ID');
echo $this->Form->text('Board.id');
echo $this->Form->input('Board.name', array('label' => '名前'));
echo $this->Form->input('Board.title', array('label' => 'タイトル'));
echo $this->Form->input('Board.content', array('label' => '内容'));
echo $this->Form->submit('送信');
echo $this->Form->end();
?>
<br />
<hr>
<br />
<table>
<?php
for($i = 0; $i < count($data); $i++) {
$arr = $data[$i]['Board'];
echo "<tr><td>{$arr['id']}</td>";
echo "<td>{$arr['name']}</td>";
echo "<td>{$arr['title']}</td>";
echo "<td>{$arr['content']}</td></tr>";
}
?>
</table>
DB の borads テーブルのプライマリーキーは id です。このため、$this->Form->input(‘Board.id’); としても入力項目としてブラウザ画面に表示されません。しかし、id も入力できるようにしたかったため、FormHelper::label と FormHelper::text を使っています。
FormHelper::input を使用して入力フォームを生成していますが、これを使用するまでにいろいろありました。詳しくはこちら→CakePHP の FormHelper::input の使い方とバリデーションとの関係を勉強します♪ | oki2a24
cake/sample/app/View/Boards/add_record.ctp
<h1>送信フォーム・サンプル</h1>
<?php echo $this->Html->link('投稿・一覧', array('controller' => 'boards', 'action' => '.')); ?>
<h2>登録・更新</h2>
<?php
echo $this->Form->create('Board', array('type' => 'post', 'action' => 'addRecord'));
echo $this->Form->label('Board.id', 'ID');
echo $this->Form->text('Board.id');
echo $this->Form->input('Board.name', array('label' => '名前'));
echo $this->Form->input('Board.title', array('label' => 'タイトル'));
echo $this->Form->input('Board.content', array('label' => '内容'));
echo $this->Form->submit('送信');
echo $this->Form->end();
?>
cake/sample/app/Controller/BoardsController.php
<?php
class BoardsController extends AppController {
public $name = 'Boards';
/**
* 初期表示
*/
public function index() {
// 初期表示。
$data = $this->Board->find('all');
// ビューで使えるように DB データをセット
$this->set('data', $data);
}
/**
* Boards テーブルにデータ追加
*/
public function addRecord() {
if ($this->request->is('post')) {
$res = $this->Board->save($this->data);
if ($res) {
$this->redirect('.');
}
}
}
}
?>
DB テーブルの情報
CREATE TABLE `boards` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `title` varchar(255) NOT NULL, `content` text NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8;
結果
http://localhost/cake/sample/boards/ で何も入力しないでボタンをクリックしましたら、http://localhost/cake/sample/boards/addRecord の画面は次のようになりました。
この画面の HTML ソースはこのようになりました。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> CakePHP: the rapid development php framework: Boards </title> <link href="/cake/sample/favicon.ico" type="image/x-icon" rel="icon" /><link href="/cake/sample/favicon.ico" type="image/x-icon" rel="shortcut icon" /><link rel="stylesheet" type="text/css" href="/cake/sample/css/cake.generic.css" /></head> <body> <div id="container"> <div id="header"> <h1><a href="http://cakephp.org">CakePHP: the rapid development php framework</a></h1> </div> <div id="content"> <h1>送信フォーム・サンプル</h1> <a href="/cake/sample/boards/.">投稿・一覧</a> <h2>登録・更新</h2> <form action="/cake/sample/boards/addRecord" id="BoardAddRecordForm" method="post" accept-charset="utf-8"><div style="display:none;"><input type="hidden" name="_method" value="POST"/></div><label for="BoardId">ID</label><input name="data[Board][id]" type="text" value="" id="BoardId"/><div class="input text required error"><label for="BoardName">名前</label><input name="data[Board][name]" maxlength="255" type="text" value="" id="BoardName" class="form-error"/><div class="error-message">名前を記入してください。</div></div><div class="input text required error"><label for="BoardTitle">タイトル</label><input name="data[Board][title]" maxlength="255" type="text" value="" id="BoardTitle" class="form-error"/><div class="error-message">タイトルを記入してください。</div></div><div class="input textarea required error"><label for="BoardContent">内容</label><textarea name="data[Board][content]" cols="30" rows="6" id="BoardContent" class="form-error"></textarea><div class="error-message">内容を記入してください。</div></div><div class="submit"><input type="submit" value="送信"/></div></form> </div> <div id="footer"> <a href="http://www.cakephp.org/" target="_blank"><img src="/cake/sample/img/cake.power.gif" alt="CakePHP: the rapid development php framework" border="0" /></a> </div> </div> <table class="cake-sql-log" id="cakeSqlLog_134241481250039fdc1e4634_45106069" summary="Cake SQL Log" cellspacing="0"><caption>(default) 0 query took ms</caption> <thead> <tr><th>Nr</th><th>Query</th><th>Error</th><th>Affected</th><th>Num. rows</th><th>Took (ms)</th></tr> </thead> <tbody> </tbody></table> </body> </html>


「CakePHP2 のバリデーションの基本を勉強します。」への1件の返信
[…] 投稿ナビゲーション ← 前へ […]