3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【cakePHP3.x】cakePHP3.x系のformHelperの使い方

Last updated at Posted at 2018-10-07

webサイトをcakePHP3で組んでいた際、応募フォームを作る過程でformの作り方を調べていたら2系と3系とで作り方が変わっていた
かつ、CSSやJSとも連携させようとすると上手くできなかったので作り方をメモ

環境
virtualbox / centOS7 / nginx / php5.6
公式ドキュメント

そもそもcakePHPのformHelperを使う意味

私は最初formHelperを使わずに自前でformタグ・inputタグを書いて、レイアウトまで整えていました
そのあと、セキュリティのこと考えないとなーと色々調べていたら、formHeplerを使うとCSRF対策のトークン関連の処理を内包してくれるとのことでした
自分でセキュリティ対策を0から組める自信がない方はformHelperを使うことをオススメします

コード例

hogehoge.ctp
<?php echo $this->Html->css('hogehoge.css') ?>
<?php echo $this->Html->script('hogehoge.js') ?>

// CSSは割愛
<div id="contact_info">
    <?=$this->Form->create(null, ['url' => ['action' => 'submit', 'type' => 'post'], 'onsubmit' => 'return send()'])?>
        <div class="tr1 clear">
            <p class="th1">名前</p>
            <div class="td1">
                <?php echo $this->Form->input('name', ['label' => false, 'templates' => ['inputContainer' => '{{content}}']]); ?>
            </div>
        </div>

        <div class="tr1 clear">
            <p class="th1">備考</p>
            <div class="td1">
                <?php echo $this->Form->input('remarks', ['label' => false, 'type' => 'textarea', 'placeholder' => 'hogehoge' ,'templates' => ['inputContainer' => '{{content}}']]); ?>
            </div>
        </div>

        <div id="contact_submit">
            <?php echo $this->Form->submit('送信', ['label' => false, 'templates' => ['submitContainer' => '{{content}}']]); ?>
        </div>
    <?=$this->Form->end()?>
</div>

▼送信ボタンが押された時に未入力チェックを行うJS

hogehoge.js
function send() {
    name = document.getElementById('name').value;

    if (name === '') {
        alert('名前が入力されていません');
        return false;
    }
}

結果

スクリーンショット 2018-10-07 20.19.47.png

個別の関数説明

▼ $this->Form->create
第2引数($options)で色々な設定を登録できます

キー 説明
url action : submit時のアクション名(関数名)
type : [post / get] 通信種別
onsubmit submit時にJSを挟む
関数からfalseがreturnされた場合、submitがキャンセルされる

▼ $this->Form->input
第1引数はコントローラで受け取る際の名前を指定する
第2引数($options)で色々な設定を登録できます

キー 説明
label input領域の左側に表示させる語句
falseで非表示
type 未入力で通常のinputタグ
textareaやradioなども指定可能
placeholder placeholderの設定が可能
templates 何も指定しない場合、inputタグがdivタグで括られる
回避策は2つ
1.'templates' => ['XXXContainer' => '{{content}}']と指定する
2.プロジェクト名/vender/cakephp/cakephp/src/View/Helper/FormHelper.phpの$_defaultConfig変数内のtemplateを書き換える

▼ $this->Form->submit
第1引数はボタン内に表示させる文字
第2引数はinputと同じ

備考

他にも色々な設定が可能です
公式ドキュメントやソースを見てみてください

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?