Export CSV in jQuery DataTable for Totara

|
| By Pawandeep Kaur

When admins or trainers want to quickly export table data from reports into a CSV file for offline use, we can use the built-in export feature of jQuery DataTable.

1. Include DataTable CSS/JS

Before using DataTables, you need to include its CSS and JavaScript libraries so the table can be styled and made interactive.

$PAGE->requires->css(new moodle_url(‘https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css’));$PAGE->requires->js(new moodle_url(‘https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js’), true);

2. Create an HTML Table

We define the structure of the table where the data will be displayed. The thead holds the column headers, and the tbody will later be filled dynamically.

// Outputecho $OUTPUT->header();

echo html_writer::start_div(‘box generalbox’);

echo html_writer::tag(‘h2’, get_string(‘pluginname’, ‘yourplugin));

$thead = html_writer::tag(‘tr’,

            html_writer::tag(‘th’, ‘ID’) .

            html_writer::tag(‘th’, ‘Name’) .

            html_writer::tag(‘th’, ‘Email’)

        );

$tbody = ;

$table = html_writer::tag(‘table’, $thead . $tbody, [

            ‘id’ => ‘myTestTable’,

            ‘class’ => ‘generaltable display’,

            ‘style’ => ‘width:100%; border-collapse: collapse;’

]);

echo $table;

echo html_writer::end_div();

3. Initialize with Server-Side Ajax

This step connects your HTML table with the database through AJAX. It dynamically loads and refreshes data from the server (Totara/Moodle backend) without reloading the page.

jQuery(document).ready(function($) {    var tableId = ‘#myTestTable’;

    table = $(tableId).DataTable({

        processing: true,

        serverSide: true,

        ajax: {

            url: M.cfg.wwwroot + ‘/report/yourplugin/ajax.php’,

            dataSrc: ‘data’

        },

        columns: [

            { data: ‘id’, title: ‘ID’ },

            { data: ‘fullname’, title: ‘Full Name’ },

            { data: ’email’, title: ‘Email’ }

        ]

    });

});

4. Include Export Button Dependencies

To add export buttons (like CSV, Excel, and PDF), you must include additional JS and CSS files from the DataTables Buttons extension.

$PAGE->requires->css(new moodle_url(‘https://cdn.datatables.net/buttons/1.6.1/css/buttons.dataTables.min.css’));$PAGE->requires->js(new moodle_url(‘https://cdn.datatables.net/buttons/1.6.1/js/dataTables.buttons.min.js’), true);

5: Add export button:

This button allows users to export the displayed table data into a CSV file. When clicked, it sends an AJAX request to the server, which then generates and downloads the file.

buttons: [

    {

        text: ‘Export CSV’,

        action: function (e, dt, node, config) {

            $.ajax({

                type: ‘POST’,

                url: ‘/report/yourplugin/ajax.php’,

                data: { export_csv: true },

                success: function (data) {

                    var a = document.createElement(“a”);

                    var blob = new Blob([\ufeff+data], { type: “text/csv;charset=utf-8;” });

                    a.href = URL.createObjectURL(blob);

                    a.download = “test_report.csv”;

                    document.body.appendChild(a);

                    a.click();

                    document.body.removeChild(a);

                }

            });

        }

    }

]

6. Handle CSV Export in ajax.php

This backend PHP code runs when the user clicks the export button. It fetches data from the database, formats it as CSV, and triggers a file download in the browser.

if (!empty($_POST[‘export_csv’]) && $_POST[‘export_csv’] === ‘true’) {      header(‘Content-Type: text/csv; charset=utf-8’);

      header(‘Content-Disposition: attachment; filename=test_report.csv’);

       $output = fopen(‘php://output’, ‘w’);

      fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

 

      fputcsv($output, [‘ID’, ‘Name’, ‘Email’]);

      $records = $DB->get_records(‘user’, null, , ‘id, firstname, lastname, email’);

      foreach ($records as $r) {

          fputcsv($output, [$r->id, fullname($r), $r->email]);

      }

      fclose($output);

      exit;

  }

Leave a Reply

Your email address will not be published. Required fields are marked *