Using Datatables in cakephp

Asked

Viewed 18 times

0

I wonder if anyone has any examples of how to use Datatables (server-side Processing) in cakephp (version 3.0 onwards). I was able to do it in php and it’s working. However, when I try to use the same idea in cakephp, I’m not getting it. I would like an example of how to build the MVC structure to use datatables. I’ve done a lot of research on the Internet, and I can’t find anything to help me. This code below lists all records in Datatable but does not limit the number of records, searches or any other action you want to do in Datatable.

class UsersController extends AppController
{

    public function index()
    {

        $connection = ConnectionManager::get('default');

         {
             $statement = $connection->prepare("SELECT * FROM Users");
             $statement->execute();
             $resultado = $statement->fetchAll();
             $totalReg= $statement->rowCount();
         }

        $query = $this->Users->find();



            if(isset($_POST["search"]["value"]))
            {
                $query .= 'WHERE Title LIKE "%'.$_POST["search"]["value"].'%" ';
                $query .= 'OR Description LIKE "%'.$_POST["search"]["value"].'%" ';
                $query .= 'OR Release LIKE "%'.$_POST["search"]["value"].'%" ';
                $query .= 'OR Rating LIKE "%'.$_POST["search"]["value"].'%" ';
                $query .= 'OR id LIKE "%'.$_POST["search"]["value"].'%" ';
            }

            if(isset($_POST["order"]))
            {
                $query .= ' ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
            }
            else
            {
            $query .= ' ORDER BY id DESC ';
            }
  

            $statement = $connection->prepare($query);
            $statement->execute();  
            $resultado = $statement->fetchAll();
            $dados = array();
            $contar_rows = $statement->rowCount();

        foreach($resultado as $row)
        {

            $sub_array = array();
            $sub_array[] = $row["0"];
            $sub_array[] = $row["1"];
            $sub_array[] = $row["2"];
            $sub_array[] = $row["3"];
            $sub_array[] = $row["4"];
            $dados[] = $sub_array;
            
        }

        $saida = array(
            "draw"              =>  intval(["draw"]),
            "recordsTotal"      =>  $contar_rows,
            "recordsFiltered"   => $totalReg,
            "data"              =>  $dados
        );


     if ($this->request->is('ajax')) {
                return $this->response
                     ->withStatus(200)
                    ->withStringBody(json_encode($saida));
             }

    }
   } 

//index.php do TEMPLATE

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css" />

<script type="text/javascript">
    $(document).ready(function() {
        $('#example').DataTable( {
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "<?= Cake\Routing\Router::url(['controller' => 'Users', 'action' => 'index']) ?>",
                "type": "POST"
            },
                    "oLanguage": {
                                "sProcessing":   "Processando...",
                                "sLengthMenu":   "Mostrar _MENU_ registros",
                                "sZeroRecords":  "Não foram encontrados resultados",
                                "sInfo":         "Mostrando de _START_ até _END_ de _TOTAL_ registros",
                                "sInfoEmpty":    "Mostrando de 0 até 0 de 0 registros",
                                "sInfoFiltered": "",
                                "sInfoPostFix":  "",
                                "sSearch":       "Buscar:",
                                "sUrl":          "",
                                "oPaginate": {
                                    "sFirst":    "Primeiro",
                                    "sPrevious": "Anterior",
                                    "sNext":     "Seguinte",
                                    "sLast":     "Último"
                                }
                            }

        } );
    } );
</script>
</head>
<body>
<table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Id</th>
                <th>Title</th>
                <th>Description</th>
                <th>Release</th>
                <th>Rating</th>

            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Id</th>
                <th>Title</th>
                <th>Description</th>
                <th>Release</th>
                <th>Rating</th>

            </tr>
        </tfoot>
    </table>
</body>
</html>

  • Welcome to Stackoverflow! Your question can be improved by presenting a reproducible example so we can comment. Suggesting where to look for examples is not the goal here.

  • I’ve entered the code. I’m waiting for suggestions.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.