Leyla
Leyla

Reputation: 103

CakePHP 3.x: multiple records from one form into multiple tables

I want to fill records from one form into several tables but I can´t find any solution. Can you give me a little example please?

Bake created this code for me.

Table:

$this->table('order');
        $this->displayField('name');
        $this->primaryKey('id');

        $this->belongsTo('Clients', [
            'foreignKey' => 'client_id',
            'joinType' => 'INNER'
        ]);

Controller:

 $order = $this->Orders->newEntity();
                if ($this->request->is('post')) {
                    $order = $this->Order->patchEntity($order, $this->request->data);
                    if ($this->Orders->save($order)) {
                       $this->Flash->success(__('Order has been saved.'));
                       return $this->redirect(['action' => 'index']);
                    } else {
                      $this->Flash->error(__('Try again.'));
                    }
                }

        $clients = $this->Orders->Clients->find('list', ['limit' => 200]);  
        $this->set(compact('order', 'clients'));
        $this->set('_serialize', ['order']);

Template:

$this->Form->create($order)
echo $this->Form->input('number', array('label' => ('Number')));
/** more inputs **/

$this->Form->create($client)
echo $this->Form->input('name');
/** more inputs **/

$this->Form->button(__('Submit');
$this->Form->end();

Thanks in advance.

Upvotes: 0

Views: 2103

Answers (1)

arilia
arilia

Reputation: 9398

as described in the documentation (link)

$this->Form->create($order)
echo $this->Form->input('number', array('label' => ('Number')));
/** more inputs **/

echo $this->Form->input('client.name');
/** more inputs **/

$this->Form->button(__('Submit');
$this->Form->end();

then in your controller

$order = $this->Orders->patchEntity(
    $order, 
    $this->request->data,
    [
        'associated' => ['Clients']
    ]
);

Note that you have an error in your code, maybe it's just a typo but: is $this->Orders->patchEntity and not $this->Order->patchEntity. The model must be plural

Upvotes: 1

Related Questions