Recently I had to save multiple rows at once using CakePHP Crud plugin. This is how I did it based on the plugin's documentation.
So, in order to save multiple rows at once, I had to modify above code to something like this.
By the way, the POSTed form data looks like this
Thanks for reading!
<?php
namespace App\Controller;
class GroceryItemsController extends AppController
{
public function add()
{
return $this->Crud->execute();
}
}
The code works but it does not actually saving anything.
So, in order to save multiple rows at once, I had to modify above code to something like this.
<?php
namespace App\Controller;
use Cake\Event\Event;
use Cake\ORM\TableRegistry;
class GroceryItemsController extends AppController
{
public function add()
{
$this->Crud->on('beforeSave', function (Event $event) {
$event->getSubject()->entity = TableRegistry::get('GroceryItems')->newEntities($this->request->getData());
});
$this->Crud->saveMethod('saveMany');
return $this->Crud->execude();
}
}
By the way, the POSTed form data looks like this
[
[
'item' => 'meat',
'price' => '12.00'
],
[
'item' => 'ketchup'
'price' => '5.00'
]
]
Thanks for reading!
Comments
Post a Comment