gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
how I can add a date range filter to datatables using Hermawan DataTables library in…
- User
how I can add a date range filter to datatables using Hermawan DataTables library in codeigniter 4
- Assistant
how I can add a date range filter to datatables using Hermawan DataTables library in codeigniter 4
To add a date range filter to a datatable using the Hermawan DataTables library in CodeIgniter 4, you can follow these steps:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<!-- Date range filter elements -->
<input type="text" id="from_date" placeholder="From Date">
<input type="text" id="to_date" placeholder="To Date">
<button type="button" id="filter">Filter</button>
<!-- Table element -->
<table id="datatable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>DOB</th>
</tr>
</thead>
</table>
$(document).ready(function () {
// Apply the datepicker to the input fields
$("#from_date, #to_date").datepicker({
dateFormat: "yy-mm-dd",
});
// Initialize the datatable with ajax settings
var table = $("#datatable").DataTable({
serverSide: true,
ajax: {
url: "<?= site_url('your_controller/load_data') ?>",
type: "POST",
data: function (d) {
d.from_date = $("#from_date").val();
d.to_date = $("#to_date").val();
},
},
columns: [{ data: "name" }, { data: "dob" }],
});
// Add click event listener to filter button
$("#filter").on("click", function () {
table.draw();
});
});
load_data() to load the table data:public function load_data()
{
// Load the library
$this->library = new \App\Libraries\Datatables();
// Define the table and its columns
$this->library->table = '
(
SELECT
name,
dob
FROM your_table
) as your_table
';
$this->library->columns = [
'name',
'dob'
];
$from_date = $this->request->getPost('from_date');
$to_date = $this->request->getPost('to_date');
if (!empty($from_date) && !empty($to_date)) {
$this->library->where = "dob BETWEEN '$from_date' AND '$to_date'";
}
// Generate the JSON output and echo
echo $this->library->generate();
}
Replace your_table with your table name, and your_controller with your controller's class name.
Now, when you click the Filter button, the table will only display rows that fall within the specified date range.
Not yet included in a published release.