CakePHP3 フォームその1
今回はCakePHPのフォームについて。 アプリケーションの基本となるフォームなのでいくつかの章に分けて。
CakePHPのフォームの処理としての流れは
1.フォームを組み込んだページを表示
2.送信先のコントローラで、送信された取り出す処理
3.何らかの結果を表示するような場合は、コントローラからビューに必要な値を設定
4.ビューで、3によって設定された値を取り出し必要に応じて画面に表示
まずは送信フォームページを作成する。
-テンプレートファイル src/Template/Hello/index.ctp
<h1>サンプル見出し</h1> <p>フォームの送信</p> <form method="get" action="/hello/sendForm"> <input type="text" name="text1" /> <input type="submit" /> </form>
-テンプレートファイル src/Template/Hello/send_form.ctp
<h1>送信結果</h1> <p><?=$result ?></p>
-コントローラファイル src/Controller/HelloController.php
<?php namespace App\Controller; class HelloController extends AppController { public function initialize(){ $this->viewBuilder()->layout('Hello'); $this->set('header','ヘッダー'); $this->set('msg','Hello/index'); $this->set('footer','Hello/footer2'); } public function index(){ } public function sendForm(){ $str = $this->request->query['text1']; $result = ""; if ($str != ""){ $result = "you type: " . $str; } else { $result = "empty."; } $this->set("result",$result); } }
これで結果画面に入力されたものが表示されるはず。
ここででてきた sendForm関数に関して、ここではフォームの情報を取り出し、ビューに渡すといった処理をしている。
requestは$thisに用意されているプロパティで、それらを扱う機能がまとめられている。 その中のqueryプロパティは「クエリーテキスト」が連想配列としてまとめられているプロパティ。
このqueryプロパティを使ってformの時に設定したname="text1" から入力されたものを受け取っている。