【发布时间】:2014-05-03 00:37:20
【问题描述】:
我创建了一个有趣的网站来学习 CakePHP,但由于某种原因,我无法获得一个多选下拉框来显示我选择的项目。在此示例中,1 个视频游戏可能有多种难度(简单、普通、困难)。在我的游戏编辑页面上,我有一个多选框来选择困难。它显示了所有三个困难,我可以选择它们并正确保存。但是,当我返回编辑页面时,我之前保存的项目不会显示为选中状态。我已验证记录已正确保存在数据库中。
表: 游戏 困难 困难游戏
型号:
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');
【问题讨论】:
-
这取决于您在控制器中执行的操作。
edit()函数是什么样的?你对变量$game做了什么?
标签: cakephp