2月 212016
 

モデルを使っていない方法です。

cakephpのチェックボックス

cakephpのチェックボックス

コントローラ

Controller/SamplesController.php

App::uses('AppController', 'Controller');

class SamplesController extends AppController {

        $rets=array(
            0=>array('pid'=>100,'title'=>'a'),
            1=>array('pid'=>200,'title'=>'b'),
            2=>array('pid'=>300,'title'=>'c'),
            3=>array('pid'=>400,'title'=>'d'),
            4=>array('pid'=>500,'title'=>'e'),
            
        );
        
        $this->set('rets',$rets);     
        
        $this->modelClass = null;
}

解説

  1. フォームの表示データを$retsに入れてコントローラから渡しています。
  2. $this->modelClass = null;を設定することで、モデルを読み込まないようにしている。

ビュー

View/samples/index.ctp

<div>
    <h3>Samples</h3>
    <table>
    <thead>
        <tr>
            <th>ckeck</th>
            <th>pid</th>
            <th>title</th>
        </tr>
    </thead>
    <tbody>
   <?php
    echo $this->Form->create(null,
      array('type'=>'post','action'=>'.')); ?>
    <?php foreach ($rets as $ret): ?>
        <tr>
            <td><?php 
            echo $this->Form->checkbox('pid.',array('value'=>$ret['pid'],'hiddenField' => false,'checked'=> @in_array($ret['pid'], $this->request->data['Sample']['pid']))); 

            ?></td>
            <td><?= h($ret['pid']) ?></td>
            <td><?= h($ret['title']) ?></td>
   
        </tr>
    <?php endforeach; ?>
    </tbody>
    </table>
   
<?php    
    echo $this->Form->end("送信");
  ?>

解説

  1. $this->Form->create()の第一引数は、モデルを使わないのでnullに。
  2. $this->Form->checkbox()の第一引数の名前にピリオドをつけることによって、nameの最後に[]がついて、data[Sample][pid][]のような配列になる。
    これを、’pid[]’と入れると、data[Sample][pid[]]のようになり、正常になっておかしくなる。
  3. $this->Form->checkbox()の第二引数の配列に’value’で値を設定できる。
  4. $this->Form->checkbox()の第二引数の配列にhiddenFieldをfalseに設定することで、 余分なhidden フィールドが生成されるのを防ぐ。
  5. $this->Form->checkbox()の第二引数の配列のcheckedは、フォーム送信後の選択状態の表示。結果は配列になり、checkboxの標準処理ではチェックできないため、in_arrayで値が選択済みかをチェック。初期状態ではrequest->dataがセットされなくてNoticeが出るので@で警告抑制。

または$this->Form->checkboxの部分を$this->Form->inputにすることもできる。

echo $this->Form->input('pid.', 
                    array(
                    'type'=>'checkbox',
                    'value'=>$ret['pid'],
                    'checked'=> @in_array($ret['pid'], $this->request->data['Sample']['pid'])
                    )
                   );

ネオビットさんを参考にさせていただきました。
http://www.neobit.jp/archives/436

よく読まれている記事

この記事を読んだ人は次の記事も読んでいます:

このエントリーをはてなブックマークに追加
はてなブックマーク - cakephp2.xチェックボックスの使いかた
[`google_buzz` not found]
[`yahoo` not found]
[`livedoor` not found]
[`friendfeed` not found]
[`tweetmeme` not found]
[`grow` not found]
[`evernote` not found]

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)