CakePHP を楽しく学べるサイトを作成しましたが、何らかの理由で、選択したアイテムを表示するための複数選択ドロップダウン ボックスを取得できません。この例では、1 つのビデオ ゲームに複数の難しさ (簡単、普通、難しい) がある場合があります。私のゲーム編集ページには、難易度を選択するための複数選択ボックスがあります。3 つすべての難易度が表示され、それらを選択して正しく保存できます。ただし、編集ページに戻ると、以前に保存した項目が選択済みとして強調表示されません。レコードがデータベースに正しく保存されていることを確認しました。
表: ゲームの難易度
モデル:
class Game extends AppModel {
public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Difficulty' =>
array(
'className' => 'Difficulty',
'joinTable' => 'difficulties_games',
'foreignKey' => 'game_id',
'associationForeignKey' => 'difficulty_id',
'unique' => 'true'
)
);
}
class Difficulty extends AppModel {
public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Game' =>
array(
'className' => 'Game',
'joinTable' => 'difficulties_games',
'foreignKey' => 'difficulty_id',
'associationForeignKey' => 'game_id',
'unique' => 'true'
)
);
}
コントローラ:
$game = $this->Game->findById($id);
$this->set('difficulties', $this->Game->Difficulty->find('list'));
表示 (edit.ctp):
echo $this->Form->input('Difficulty');
これは私が見逃している単純なものでなければなりませんが、HABTM に関する本を読み、ここで検索しましたが、複数選択ボックスについてはあまり見つかりませんでした。
アップデート:
コントローラーの編集機能全体を次に示します。
public function edit($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$game = $this->Game->findById($id);
if (!$game) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->Game->id = $id;
if ($this->Game->saveAll($this->request->data)) {
$this->Session->setFlash('Your game has been updated.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash($this->Game->invalidFields());
}
}
if (!$this->request->data) {
$this->request->data = $game;
}
$this->set('systems', $this->Game->System->find('list'));
$this->set('genres', $this->Game->Genre->find('list'));
$this->set('difficulties', $this->Game->Difficulty->find('list'));
}
また、ビューに関する詳細は次のとおりです。
echo $this->Form->create('Game');
echo $this->Form->input('name');
echo $this->Form->input('system_id');
echo $this->Form->input('genre_id');
echo $this->Form->input('Difficulty');
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->end('Save Game');