Skip to main content

CakePHP 3 Crud plugin and DataTables serverside processing

Today I am going to share how to consume JSON data from CakePHP Crud Plugin into jQuery DataTables.



First you need to set up CakePHP Crud in your controller. We need to load Crud.Api listener in order to serve data in json format.
<?php

namespace App\Controller;

class OrdersController extends AppController
{
    use \Crud\Controller\ControllerTrait;
    
    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('Crud.Crud', [
            'actions' => [
                'index' => [
                    'className' => 'Crud.Index',
                ],
            ],
            'listeners' => [
                'Crud.Api'
            ]
        ]);
    }

    public function index()
    {
        return $this->Crud->execute();
    }
}


Then in your js datatables ajax configuration
let dt = $('#order-table').DataTable({
    processing: true,
    serverSide: true,

    columns: [
      // define your own columns
    ],


    ajax: {
      url: '/orders.json',
      dataFilter: function (data) {
        let json = jQuery.parseJSON(data);
        json.recordsTotal = json.pagination.count;
        json.recordsFiltered = json.pagination.count;

        return JSON.stringify(json);
      },
      data: function (d, settings) {
        let api = new $.fn.dataTable.Api(settings);
        
        d.query = d.search.value;

        d.page = Math.min(
          Math.max(0, Math.round(d.start / api.page.len())),
          api.page.info().pages
        );
        d.page = d.page + 1;
        d.limit = d.length;
      },
    }
  });



That's it!

Comments

Popular posts from this blog