CakePHP 3:编辑 belongsToMany 模型时预选复选框

CakePHP 3: Preselect checkboxes when editing belongsToMany Model

我有一个Workshop模型,属于很多Speaker通过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'
        ]);
    }
}

创建研讨会并为研讨会分配演讲者和时间效果很好。但是,如果我想编辑一个研讨会,可能的演讲者会出现,但分配的演讲者不会自动预select(保存工作,如果我在编辑时只是 select 一些演讲者 - 分配的时间也被自动预selected)。我在 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()

/**
 * 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']);
}

在我的创意工坊实体中,我还指定了 "speakers" 可访问:

protected $_accessible = [
    'title' => true,
    'date' => true,
    'description' => true,
    'type' => true,
    'sort' => true,
    'meta' => true,
    'time_id' => true,
    'speakers' => true,
];

我正在使用 Speaker 的虚拟字段在复选框下方显示名字和姓氏。在 SpeakersTable::initialize():

$this->displayField('full_name');

在演讲者实体中:

protected function _getFullName() {
    return $this->_properties['first_name'].' '.$this->_properties['last_name'];
}

tl;dr:正在显示可用的演讲者列表,但在编辑研讨会时未预先select编辑与研讨会相关的演讲者。其他一切正常。

问题已解决,我忘记在 WorkshopsController::edit() 中添加 contain 选项值。

$workshop = $this->Workshops->get($id, [
    'contain' => ['Speakers']
]);

我没有看到,添加选项后它正在工作,因为我试图同时在 edit.ctp 中手动 select 复选框,这重置了它们。