Use Datatable in CodeIgniter
Home » BLOG » Web development » How To Use DataTables In Codeigniter

How To Use DataTables In Codeigniter

category:  CodeIgniter, Web development
4 min read

When you work on a web application or the back-end of your website, you often create reports for the users. The reports will display in the table style. Also, you will have the requirements from the users to add the pagination, search, ability to select the number of records per page, and export data as Excel, CSV, and PDF file. Those features can be done with Datatable plugin.

What is Datatable plugin

Datatable plugin is an advanced interactive control JavaScript plugin. With Datatable, you can do the pagination, instant search, various type of data sources, integrated into your theme (Bootstrap framework for example), responsive, mobile-friendly, and much more.

Use Datatable in CodeIgniter

Since Datatable is the JavaScript plugin, you will use it in the view page. You will create the data source in the controller and render the data source in the Datatable plugin on the view page. Let’s start.

Download or Using CDN version

You can download the Datatable plugin or using the CDN version.

Then you will include the Datatable style to the head tag in your template as below.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter | News</title>    
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">

Next, you will include the Datatable scripts to the footer tag in your template as below.

<script src="https://code.jquery.com/jquery-3.5.1.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js" type="text/javascript"></script>

</body>
</html>

Datatable plugin needs the jQuery library as dependency. So you will need to load the jQuery library first. Then you will load the Datatable plugin.

Create the data source in the controller

In the controller, I will query the data and pass the query result to the view page. Below is my sample code.

    public function reports()
    {
        $news = $this->news_model->get_news();
        $data['news'] = $news;

        $this->load->view('templates/header');
        $this->load->view('news/reports', $data);
        $this->load->view('templates/footer');
    }

Create the query in the model

I query the news data from the get_news method from my news_model Model. In my News_model model will look like this.

    /**
    * @return string array 
    */
    public function get_news($slug = FALSE)
    {
        if ($slug === FALSE) {
            $query = $this->db->get('news');
            return $query->result_array();
        }

        $query = $this->db->get_where('news', array('slug' => $slug));
        return $query->row_array();
    }

In the get_news method, we return the query result as an array which Datatable needs the array format as the data source.

The query result array will look like this.

array(
 array(
    'id' => '1',
    'title' => 'This is a news1',
    'slug' => 'news-1',
    'text' => 'dummy text'
  ),
 array(
    'id' => '2',
    'title' => 'This is a news2',
    'slug' => 'news-2',
    'text' => 'dummy text'
  ),
)

In some cases, you may get the data via API. For example, you want to get the data from API using cURL. So in your controller, you will add the cURL command below.

$cURLConnection = curl_init();
curl_setopt($cURLConnection, CURLOPT_URL, 'YourAPI');
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
$newsList = curl_exec($cURLConnection);
curl_close($cURLConnection);
$json_arr_response = json_decode($newsList);
/* Once you get the result from cURL, you must convert the result to be the DataTable data format as the query result array above ( array(array()) ). */

Create the template in the view

In the view page, I create the table HTML tag as below.

<div class="container">
    <div class="row">
        <div class="col-md-12">

            <!-- Render data in datatable plugin -->
            <table id="rep_news" class="table table-striped table-bordered table-hover" style="width:100%">
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Title</th>
                        <th>Slug</th>
                        <th>Text</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th>Id</th>
                        <th>Title</th>
                        <th>Slug</th>
                        <th>Text</th>
                    </tr>
                </tfoot>
            </table>
            <!-- table ends -->
        </div>
    </div>
</div>

Call the Datatable plugin

At the end of template, we will call the Datatable function as the code below.

<script src="https://code.jquery.com/jquery-3.5.1.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js" type="text/javascript"></script>

<script>
     // # After the HTML and CSS load, we will call the Datatable plugin via DataTable function.
    $(document).ready(function() {
        $('#rep_news').DataTable({
            data: <?php echo json_encode($news) ?>,
            // columns option is optional. You can limit the columns to display to the view page by setting the columns option.
            columns: [{
                    "data": "id"
                },
                {
                    "data": "title"
                },
                {
                    "data": "slug"
                },
                {
                    "data": "text"
                }
            ]
        });
    });
</script>

</body>
</html>

You will see we pass a $news array which is queried the data from our model. We pass the $news array to the data option of the Datatable plugin. Also, we convert the $news array to a JSON object with json_encode PHP function.

And that’s it. Datatable will map the $news data to the table header and footer tag where we create on the view page.

Data in Datatable plugin

Below is an example of how the data will look like in Datatable plugin by using the default Datatable configuration.

feature datatable codeigniter
figure: Using Datatable plugin in CodeIgniter

Useful Links

Below is the useful links for Datatable plugin:

  • Examples (initialization, data sources, API, Ajax, and more)
  • Options (column rendering and more)
  • Manual
  • Reference
  • Extensions (autofill, buttons, responsive, search panes)
  • Plug-ins (sorting, filtering, pagination, internationalization, data renderer)

Conclusion

With the Datatable plugin, the user can view the data in an efficient way. In the developer view, the plugin is very easy to use. It is customizable. Also, the documentation is well written. If you stuck on some issues, you can ask the community at Datatable forums or pay for full forum access. The price is affordable and worth it.