CakePHP4でチェックボックスなどの複数選択は配列でPost送信されてコントローラで受け取ります。これを文字列に変換して保存する方法をメモします。
配列を文字列に変換したり、戻したりするには、PHPの「implode」「explode」を使います。
コントローラ側
src\Controller\BotsController.php
// src\Controller\BotsController.php
class BotsController extends AppController
:
:
:
public function edit($id = null)
{
if ($this->request->is(['patch', 'post', 'put'])) {
//1受け渡されたリクエストを取得
$arrTags = $this->request->getData('tags')
//2配列を文字列に変換
$strTags = implode(',', $strTags)
//3リクエストを取得、書き換え、新たなリクエストにセットしなおす
$this->setRequest($this->getRequest()->withData('tags',$strTags));
//上記1~3をまとめたコード
$this->setRequest(
$this->getRequest()->withData(
'tags',implode(',', $this->request->getData('tags'))
)
);
//ここからは通常の保存
$bot = $this->Bots->patchEntity($bot, $this->request->getData());
if ($this->Bots->save($bot)) {
$this->Flash->success(__('The bot has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The bot could not be saved. Please, try again.'));
}
$this->set(compact('bot'));
}
ビュー側
templates\Bot\edit.php
//フォーム内で
//複数選択をチェックボックスで表示
$arrTagLists = [ 'tora' => 'トラ', 'wani' => 'ワニ', 'panda' => 'パンダ' ];
//
echo $this->Form->control('tags',
[
'multiple'=> 'checkbox',
'label'=>'チェックボックスを選択して下さい',
//選択候補を指定するオプション
'options' => $arrTagLists ,
//選択済みを指定するオプション
//https://book.cakephp.org/4/ja/views/helpers/form.html#checkbox-radio-select-options
'value' => explode(',', $bot['tags'])
]);
参考ブログ
【cakePHP4】フォームデータを書き換えする
【Cakephp4】GETリクエストに値を任意にセットする方法
CookBook セレクト、チェックボックス、ラジオに関するオプション
公式のコードから引用、複数選択要素をselectedを付ける方法
multiple 属性を true に設定した select コントロールでは
デフォルトで選択したい値の配列を使うことができます。
// https://book.cakephp.org/4/ja/views/helpers/form.html#checkbox-radio-select-options
// 値に 1 と 3 を持つ HTML <option> 要素が事前選択されて描画されます。
echo $this->Form->select(
'rooms',
[1, 2, 3, 4, 5],
[
'multiple' => true,
'value' => [1, 3]
]
);