CakePHP 1.2 で複数チェックボックス(その3)
http://book.cakephp.org/ja/view/193/options-multiple
「'multiple' => true」は、知っていたが、
「'multiple' => 'checkbox'」なるものがあるとはしらなんだ。
<?php echo $form->input("User.hobby", array('type' => 'select', 'multiple' => 'checkbox', 'options' => array(1 => '映画', '釣り'))); ?>
以下の記事も一応動作しているがもう少しスマートな方法が利用できるわけだ。
過去の記事:
過去記事のプログラムを修正してみた。
<?php class User extends AppModel { var $name = "User"; var $checkboxes = array("hobby"); function beforeSave() { foreach ($this->checkboxes as $field) { if (!array_key_exists($field, $this->data[$this->name])) { continue; } $result = ""; foreach ($this->data[$this->name][$field] as $key => $value) { if ($result == "") { $result = $value; } else { $result .= "," . $value; } } $this->data[$this->name][$field] = $result; } return true; } function afterFind($results, $primary = false) { for ($i = 0; $i < count($results); $i++) { foreach ($this->checkboxes as $field) { if (!array_key_exists($field, $results[$i][$this->name])) { continue; } $a = split(',', $results[$i][$this->name][$field]); $results[$i][$this->name][$field] = $a; } } return $results; } }