Skip to main content

How to save multiple records at once using CakePHP 3 Crud plugin

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.
<?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

Popular posts from this blog