Using Datatables with the Editor extension, it sends data to the server to be processed. The client sends three fields: action
, id
and data
. The action can be create
, edit
or delete
. The id is only filled in for edit
.
So in short, you can use this controller:
<?php
namespace MyModule\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
class DatatablesController extends AbstractActionController
{
public function saveAction()
{
if (!$this->getRequest()->isPost()) {
$response = $this->getResponse();
$response->setStatusCode(405); // Method not allowed
return $response;
}
$action = $this->params()->fromPost('action', null);
$data = array();
switch ($action) {
case 'create':
$data = $this->createRow();
break;
case 'edit':
$data = $this->editRow();
break;
case 'delete':
$data = $this->deleteRow();
break;
default:
$response = $this->getResponse();
$response->setStatusCode(422); // Unprocessable entity
return $response;
}
$model = new JsonModel($data);
return $model;
}
protected function createRow()
{
$data = $this->params()->fromPost('data', array());
// Create a new entity with $data
// Return the properties from the new entity
return array();
}
protected function editRow()
{
$id = $this->params()->fromPost('id');
$data = $this->params()->fromPost('data', array());
// Fetch the entity with id $id
// Update the entity with $data
// Return the properties from the entity
return array();
}
protected function deleteRow()
{
$ids = $this->params()->fromPost('data', array());
// Remove all entities with an id in the array $ids
}
}