Jeffrey L. Roberts
Jeffrey L. Roberts

Reputation: 2994

CakePHP 3.x - Save many-to-many data

I am attempting to patchEntity with a join table, but I am unable to get it to save the associated records, and I think I have the backend code correct, but I am unsure of what the frontend code should look like...

Here is the scenario, I have three tables

Ledgers Table

id int
title string

Tribes Table

id int
name string

LedgersTribes Table

id int
ledger_id int
tribe_id int

Here is my backend code

public function ledgerSave($id = null)
{
    $this->loadModel('Ledgers');

    $ledger = $this->Ledgers->get($id, [
        'contain' => ['LedgersTribes']
    ]);

    if ($this->request->is(['patch', 'post', 'put'])) {
         $ledger = $this->Ledgers->patchEntity($ledger, $this->request->getData(), [
             'associated' => ['LedgersTribes']
         ]);
         if ($this->Ledgers->save($ledger)) {
             $this->Flash->success(__('The ledger has been saved.'));

             return $this->redirect($this->referer());
         }
         $this->Flash->error(__('The ledger could not be saved. Please, try again.'));
    }
    $this->set(compact('ledger'));
}

Here is the relevant frontend code

<?= $this->Form->control('tribe_id[]', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal', 'value' => $tribe->id]) ?>

My question is, what should the field name be for the tribe_id, the idea is, i have a list of checkboxes and the user checks off a couple of boxes and then those tribe_id's get inserted into the LedgersTribes table with the ledger_id

Any ideas on how I can do this?


EDIT: Here is a screenshot of the form

enter image description here


I have reviewed the following links, and none of them answer my question...

CakePHP 3: Save Associated Model Fail

Save associated in cakephp 3 not working

How to save associated joinData in cakephp 3.x

CakePHP 3 cannot save associated model

Cakephp 3 - Save associated belongsToMany (joinTable)

Upvotes: 2

Views: 258

Answers (2)

harpax
harpax

Reputation: 6106

This should do:

echo $this->Form->control('tribes._ids[]', [        
    'type' => 'checkbox', 
    'label' => false, 
    'class' => 'minimal', 
    'value' => $tribe->id]
]);

This is described here: https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-data

Upvotes: 1

Shohidur Rahman
Shohidur Rahman

Reputation: 1

I think you have to get the table (ex: TableRegistry::getTableLocator()->get('')) where you want to save the data. Then create entity from that and save the data, hopefully it will work.

Upvotes: -1

Related Questions