2
votes

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)

2
Your code looks like it would only allow to choose from already associated records, ie only from tribes that are already associated with the selected ledge, instead of from all existing tribes... is that really what you want to do?ndm
I have added a screenshot of the form, I would like to be able to check one or more of the tribes and have those tribes saved to the LedgersTribes join tableJeffrey L. Roberts

2 Answers

1
votes

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

-1
votes

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.