I am using 3 tables:
newsmessages, groups and groups_newsmessages.
They have the following layout in the DB:
newsmessages:
- id
- title
- content
groups:
- id
- group_name
groups_newsmessages:
- id
- group_id
- newsmessage_id
So I am able to edit a newsmessage and add ids of groups I select (can be multiple) combined with the newsmessage id in the “groups_newsmessages” table, with the follow code:
public function edit($id = null)
{
$this->set('title', 'Bewerk nieuwsbericht');
$this->viewBuilder()->setLayout('admin');
$newsmessage = $this->Newsmessages->get($id, [
'contains' => ['Groups', 'Webpages']
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$newsmessage = $this->Newsmessages->patchEntity($newsmessage, $this->request->getData());
if ($this->Newsmessages->save($newsmessage)) {
$this->Flash->success(__('The newsmessage has been saved.'));
return $this->redirect(['action' => 'manage']);
}
$this->Flash->error(__('The newsmessage could not be saved. Please, try again.'));
}
$groups = $this->Newsmessages->Groups->find('list', [
'keyField' => 'id',
'valueField' => 'group_name']);
$webpages = $this->Newsmessages->Webpages->find('all', [
'conditions' => ['Webpages.isblog = ' => 1],
'limit' => 200
]);
$this->set(compact('newsmessage', 'groups', 'webpages'));
}
On the edit page I have the code setup like:
<div class="form-group mt-3 show-groups d-none">
<?= $this->Form->input('groups._ids',
[
'options' => $groups,
'id' => 'group_id',
'class' => 'form-control'
])
?>
</div>
But what I am unable to do is pre-select groups I have added to the table already, so when loading the edit page from a specific newsmessage, it already shows the groups I have added the newsmessage to.
Thanks for any help.