CodeIgniter 4 - Server Side DataTable Example Tutorial

Apr 21, 2022

.

Admin

CodeIgniter 4 - Server Side DataTable Example Tutorial

Hi Guys,

In this post, we will learn codeigniter 4 server side datatable tutorial. In this article, we will implement a how to implement and use datatables in codeigniter 4. let’s discuss about codeigniter 4 datatables tutorial. you will learn yajra datatables codeigniter 4 example. follow bellow step for how to implement and use datatables in codeigniter 4.

Today, I will let you know example of codeigniter 4 server side datatable tutorial. if you have question about how to implement and use datatables in codeigniter 4 then I will give simple example with solution.

Datatables Provides a in-built functionalities such as Data Sorting, Searching, Pagination, and Filtering is a widely used and most popular JavaScript library to display data in a tabular form.

Step 1: Install Codeigniter 4


This is optional; however, if you have not created the codeigniter app, then you may go ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news

Step 2: Configure Database Connection

add your database name, username and password in application/config/database.php file and establish the database connection.

public $default = [

'DSN' => '',

'hostname' => 'localhost',

'username' => 'root',

'password' => '',

'database' => 'demo',

'DBDriver' => 'MySQLi',

'DBPrefix' => '',

'pConnect' => false,

'DBDebug' => (ENVIRONMENT !== 'production'),

'cacheOn' => false,

'cacheDir' => '',

'charset' => 'utf8',

'DBCollat' => 'utf8_general_ci',

'swapPre' => '',

'encrypt' => false,

'compress' => false,

'strictOn' => false,

'failover' => [],

'port' => 3306,

];

You can direct execute the SQL query from PHPMyAdmin to create the users table and insert some random data into it to save your time.

CREATE DATABASE demo;

CREATE TABLE users (

id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',

name varchar(100) NOT NULL COMMENT 'Name',

email varchar(255) NOT NULL COMMENT 'Email Address',

PRIMARY KEY (id)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo database' AUTO_INCREMENT=1;

INSERT INTO `users` (`id`, `name`, `email`) VALUES

(1, 'Bhavesh', 'bhavesh@gmail.com'),

(2, 'Vishal', 'vishal@gmail.com'),

(3, 'Nikhil', 'nikhil@gmail.com'),

(4, 'John Doe', 'john@gmail.com'),

(5, 'Paul Bettany', 'paul@gmail.com'),

(6, 'Vanya', 'vanya@gmail.com'),

(7, 'Luther', 'luther@gmail.com'),

(8, 'Wayne Barrett', 'wayne@gmail.com'),

(9, 'Vincent Ramos', 'ramos@gmail.com'),

(10, 'Susan Warren', 'sussan@gmail.com'),

(11, 'Jason Evans', 'jason@gmail.com'),

(12, 'Madison Simpson', 'madison@gmail.com'),

(13, 'Marvin Ortiz', 'paul@gmail.com'),

(14, 'Felecia Phillips', 'felecia@gmail.com'),

(15, 'Tommy Hernandez', 'hernandez@gmail.com');

Step 3: Installing CodeIgniter4 DataTables

To install datatable pluing by executing the following comamnd on terminal:

composer require hermawan/codeigniter4-datatables

then open app/Config/autoload.php. add namespace to $psr4 array. see the code below:

app/Config/autoload.php

public $psr4 = [

APP_NAMESPACE => APPPATH, // For custom app namespace

'Config' => APPPATH . 'Config',

'PHPSQLParser' => APPPATH .'ThirdParty/php-sql-parser/src/PHPSQLParser',

'Hermawan\DataTables' => APPPATH .'ThirdParty/CodeIgniter4-DataTables/src'

];

Step 4: Create New Model

In this step create a UserModel.php file in the app/Models/ diretory, then copy the following given below code.

app/Models/UserModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model

{

protected $table = 'users';

protected $primaryKey = 'id';

protected $allowedFields = ['name', 'email'];

}

Step 5: Create Controller

In this step we will need to create a new controller DatatableController.php file and add then copy the following given below code.

app/Controllers/DatatableController.php

<?php

namespace App\Controllers;

use \CodeIgniter\Controller;

use \Hermawan\DataTables\DataTable;

class DatatableController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

helper('url');

return view('userView');

}

/**

* Write code on Method

*

* @return response()

*/

public function ajaxDataTables()

{

$db = db_connect();

$builder = $db->table('users')->select('name, email, id');

return DataTable::of($builder)

->addNumbering() //it will return data output with numbering on first column

->toJson();

}

}

?>

Step 6: Create Routes

In this step, we require to create a route that will be using to display the users list within the Datatables. To generate the routes add the following code inside the app/Config/Routes.php file.

app/Config/Routes.php

$routes->setDefaultController('UsersController');

$routes->get('list', 'UsersController::index');

$routes->get('ajax-datatable', 'UsersController::ajaxDataTables');

Step 7: Display Datatables in Codeigniter

In this step, we will render the data from database and display in Codeigniter template using DataTables. We have included the Datatables CDN link of jQuery and CSS in the footer.

app/Views/userView.php

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>CodeIgniter 4 - Server Side DataTable Example Tutorial - Nicesnippets.com</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css">

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css" >

<link href="https://cdn.datatables.net/1.10.24/css/dataTables.bootstrap4.min.css">

</head>

<body>

<div class="container">

<h1 style="font-size:20pt"></h1>

<h3>Customers Data</h3>

<table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">

<thead>

<tr>

<th>No</th>

<th>Name</th>

<th>Email</th>

</tr>

</thead>

<tbody></tbody>

<tfoot>

<tr>

<th>No</th>

<th>Name</th>

<th>Email</th>

</tr>

</tfoot>

</table>

</div>

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>

<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>

<script src="https://cdn.datatables.net/1.10.24/js/dataTables.bootstrap4.min.js"></script>

<script type="text/javascript">

/*------------------------------------------

--------------------------------------------

DataTable

--------------------------------------------

--------------------------------------------*/

$(document).ready(function() {

$('#table').DataTable({

processing: true,

serverSide: true,

order: [],

ajax: "<?php echo site_url('ajax-datatable')?>",

columnDefs: [

{ targets: 0, orderable: false},

]

});

});

</script>

</body>

</html>

Step 8 : Run Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8080/

It will help you...

#Codeigniter 4