PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

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

 February 21, 2022     cakephp, cakephp-3.0     No comments   

Issue

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.


Solution

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



Answered By - arilia
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing