我有一个Workshop模型,通过workshop_speakers属于很多演讲者:
class WorkshopsTable extends Table
{
public function initialize(array $config)
{
$this->table('workshops');
$this->displayField('title');
$this->primaryKey(['id']);
$this->belongsTo('Times', [
'foreignKey' => 'time_id',
'joinType' => 'INNER'
]);
$this->belongsToMany('Speakers', [
'foreignKey' => 'workshop_id',
'targetForeignKey' => 'speaker_id',
'joinTable' => 'speakers_workshops'
]);
}
}
创建研讨会,分配演讲者和研讨会的时间很好。但是,如果我想编辑一个工作室,可能的扬声器会显示,但指定的扬声器不会自动预选(保存工作,如果我只是在编辑时选择一些扬声器 - 指定的时间也会自动预选)。我在edit.ctp中的输入看起来像这样:
<?= $this->Form->create($workshop); ?>
...
echo $this->Form->input('time_id', ['type' => 'select', 'multiple' => false, 'class' => 'form-control']);
echo $this->Form->input('speakers._ids', ['multiple' => 'checkbox']);
WorkshopsController ::编辑()
/**
* Edit method
*
* @param string|null $id Workshop id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$workshop = $this->Workshops->get($id, [
'contain' => ['Speakers']
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$workshop = $this->Workshops->patchEntity($workshop, $this->request->data);
if ($this->Workshops->save($workshop)) {
$this->Flash->success('The workshop has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The workshop could not be saved. Please, try again.');
}
}
$times = $this->Workshops->Times->find('list');
$speakers = $this->Workshops->Speakers->find('list');
$this->set(compact('workshop', 'times', 'speakers'));
$this->set('_serialize', ['workshop']);
}
在我的工作坊中,我还指派了#34;发言人&#34;如可访问:
protected $_accessible = [
'title' => true,
'date' => true,
'description' => true,
'type' => true,
'sort' => true,
'meta' => true,
'time_id' => true,
'speakers' => true,
];
我正在使用Speaker的虚拟字段来显示Checkboxes下面的名字和姓氏。在SpeakersTable :: initialize()中:
$this->displayField('full_name');
在演讲者实体中:
protected function _getFullName() {
return $this->_properties['first_name'].' '.$this->_properties['last_name'];
}
tl; dr:正在显示可用的发言人列表,但在编辑工作室时未预先选择与讲习班相关的演讲者。其他一切都很好。
答案 0 :(得分:2)
问题解决了,我忘了在WorkshopsController :: edit()中添加contains选项值。
$workshop = $this->Workshops->get($id, [
'contain' => ['Speakers']
]);
我没有看到,添加该选项后它正在工作,因为我试图同时在edit.ctp中手动选中复选框,重置了它们。