Search code examples
cakephpcakephp-3.0cakephp-3.4

Saving hasMany relation in add form in cakephp 3


I have a Shop that can have many Offers and I would like to create a new Shop and a number of Offers in the add form of the Shop.

From what I read the fields should look something like this

<?= $this->Form->control('offers.0.name', ['value' => 'awesome']); ?>

But I get a form error because the shop_id for the Offer is missing.

How do I structure my form to save the Shop and the Offers and cake fills in the newly created shop_id for the Offers.


Solution

  • //In Controller,

    $shopTable=TableRegistry::get('Shop');
    $entity = $shopTable->newEntity($this->request->getData(), [
               'associated' => [
                    'Offers'
                ]
              ]);
    

    OR, Same as patchEntity with associated ,you can do.