PHP code example of ngekoding / codeigniter-datatables
1. Go to this page and download the library: Download ngekoding/codeigniter-datatables library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
ngekoding / codeigniter-datatables example snippets
// CodeIgniter 3 Example
// Here we will select all fields from posts table
// and make a join with categories table
// IMPORTANT! We don't need to call ->get() here
$queryBuilder = $this->db->select('p.*, c.name category')
->from('posts p')
->join('categories c', 'c.id=p.category_id');
// The library will automatically detect the CodeIgniter version you are using
$datatables = new Ngekoding\CodeIgniterDataTables\DataTables($queryBuilder);
$datatables->generate(); // done
// CodeIgniter 4 Example
$db = db_connect();
$queryBuilder = $db->from('posts p')
->select('p.*, c.name category')
->join('categories c', 'c.id=p.category_id');
// The library will automatically detect the CodeIgniter version you are using
$datatables = new Ngekoding\CodeIgniterDataTables\DataTables($queryBuilder);
$datatables->generate(); // done
$datatables->asObject()
->generate();
// General, use the second param to define the version (3 or 4)
$datatables = new Ngekoding\CodeIgniterDataTables\DataTables($queryBuilder, 3);
// CodeIgniter 3
$datatables = new Ngekoding\CodeIgniterDataTables\DataTablesCodeIgniter3($queryBuilder);
// CodeIgniter 4
$datatables = new Ngekoding\CodeIgniterDataTables\DataTablesCodeIgniter4($queryBuilder);
$datatables = new Ngekoding\CodeIgniterDataTables\DataTables($queryBuilder);
// Return the output as objects instead of arrays
$datatables->asObject();
// Only return title & category (accept string or array)
$datatables->only(['title', 'category']);
// Return all except the id
// You may use one of only or except
$datatables->except(['id']);
// Format the output
$datatables->format('title', function($value, $row) {
return '<b>'.$value.'</b>';
});
// Add extra column
$datatables->addColumn('action', function($row) {
return '<a href="url/to/delete/post/'.$row->id.'">Delete</a>';
});
// Add column alias
// It is very useful when we use SELECT JOIN to prevent column ambiguous
$datatables->addColumnAlias('p.id', 'id');
// Add column aliases
// Same as the addColumnAlias, but for multiple alias at once
$datatables->addColumnAliases([
'p.id' => 'id',
'c.name' => 'category'
]);
// Add squence number
// The default key is `sequenceNumber`
// You can change it with give the param
$datatables->addSequenceNumber();
$datatables->addSequenceNumber('rowNumber'); // It will be rowNumber
// Don't forget to call generate to get the results
$datatables->generate();
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.