我有一个工作坊模型,通过workshops_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'
]);
}
}
创建讲习班、指派演讲者并为其安排时间都很顺利。然而,如果我想编辑一个讲习班,可能的演讲者会出现,但是指定的演讲者不会自动预先选定(如果我在编辑时仅选择了一些演讲者,则保存将起作用-指定的时间也会自动预先选定)。我的编辑.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()
/**
* 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']);
}
在我的 Workshop 实体中,我还将 "speakers" 指定为可访问的:
protected $_accessible = [
'title' => true,
'date' => true,
'description' => true,
'type' => true,
'sort' => true,
'meta' => true,
'time_id' => true,
'speakers' => true,
];
我在使用虚拟字段来显示讲者的名字和姓氏在复选框下方。在SpeakersTable::initialize()中:
$this->displayField('full_name');
在扬声器实体中:
protected function _getFullName() {
return $this->_properties['first_name'].' '.$this->_properties['last_name'];
}
简述:显示可用演讲者列表,但在编辑研讨会时未预先选择与研讨会相关的演讲者。其他所有功能都正常。
edit()
操作代码和Form::create()
调用。另外,顺便提一下,您的第一个代码示例有问题,方法调用应该在initialize()
方法中。 - ndm