belongsToMany – multiple checkboxes

Powiązanie belongsToMany w postaci checkbox-ów. Tabele   usersrecommendations_usersrecommendations

Entity User

protected $_accessible = [
    ....
   'recommendations' => true,
];

Tabela UsersTable

$this->belongsToMany('Recommendations', [
    'saveStrategy' => 'replace'
]);

Kontroler UsersController

$user = $this->Users->get($id, [
             'contain' => ['Recommendations'],
         ]);

if ($this->request->is(['patch', 'post', 'put'])) {
   
  // Nie dodaje rekomendacji tylko aktualizuje
  $user = $this->Users->patchEntity($user, $this->request->getData(), [ 
                         'associated' => [
                               'Recommendations' => ['onlyIds' => true]
                          ] 
                        ]);
  if ($this->Users->save($user)) {
      $this->Flash->success(__('Zapisane.'));
      return $this->redirect(['action' => 'view', $user->id]);
  }
  $this->Flash->error(__('Nie można zapisać.'));
} // POST

$recommendations = $this->Users->Recommendations->find('list')
                        ->where(['is_active' => 1])
                        ->order(['name'])
                        ->all();

$this->set(compact('user', 'recommendations'));

Szablon Users/view

<?= $this->Form->create($user) ?>

<div class="border p-2 mb-2">
    <?= $this->Form->control('recommendations._ids', [
            'class'    => 'mr-2',
            'options'  => $recommendations,
            'multiple' => 'checkbox',
            'label'    => false
           ])
    ?>
</div>

<?= $this->Form->end() ?>