Skip to content

Instantly share code, notes, and snippets.

@tranchausky
Created October 15, 2021 04:32
Show Gist options
  • Select an option

  • Save tranchausky/6ebf069770f6331a1243758cb5a998b2 to your computer and use it in GitHub Desktop.

Select an option

Save tranchausky/6ebf069770f6331a1243758cb5a998b2 to your computer and use it in GitHub Desktop.
DataTables Class for codeigniter 2,3
<?php
public function search_datatable()
{
$this->load->library('Datatables',null,'datatables');
$this->datatables->setDatabase('default');
$aTable = 'manage_media_files';
$aColumns = array('id','name','file_size','file_type','create_at','create_by','folder_id');
$folderId = $this->input->post('folder_id');
$whereMore = [
'folder_id' => $folderId
];
$json = $this->datatables->get_json($aTable, $aColumns, $whereMore);
return $this->output->set_output($json);
}
<?php
//update from https://datatables.net/forums/discussion/44562/datatables-1-10-with-codeigniter-3-1-5
class DataTables
{
protected $CI;
private $database;
public function __construct()
{
$this->CI = &get_instance();
}
public function setDatabase($database)
{
$this->database = $database;
}
public function getDatabase()
{
return $this->database;
}
public function get_json($aTable = NULL, $aColumns = NULL, $whereMore = [])
{
// Load CI Database library
$this->CI->load->database($this->database);
// Read dataTables POST variables
$iDraw = $this->CI->input->post('draw');
$iColumns = $this->CI->input->post('columns');
$iOrder = $this->CI->input->post('order');
$iStart = $this->CI->input->post('start');
$iLength = $this->CI->input->post('length');
$iSearch = $this->CI->input->post('search');
$recordsTotal = $this->countAllWhere($aTable, $whereMore);
$recordsFiltered = $recordsTotal;
if (isset($iSearch) && $iSearch['value'] != '') {
$this->CI->db->where($whereMore);
$listWhereOr = [];
for ($i = 0; $i < count($aColumns); $i++) {
if ($aColumns[$i] == $iColumns[$i]['data'] && $iColumns[$i]['searchable'] == 'true') {
$listWhereOr[] = '`'.$aColumns[$i] .'` Like "%' .$iSearch['value'].'%"';
}
}
$listWhereOr = implode(' OR ',$listWhereOr);
$listWhereOr ='('.$listWhereOr.')';
$this->CI->db->where($listWhereOr, null, false);
$recordsFiltered = $this->CI->db->count_all_results($aTable, false);
}
$this->CI->db->where($whereMore);
if (isset($iSearch) && $iSearch['value'] != '') {
$this->CI->db->where($listWhereOr, null, false);
}
$this->CI->db->select(implode(',', $aColumns));
// Ordering
if (isset($iOrder[0])) {
for ($i = 0; $i < count($iOrder); $i++) {
$this->CI->db->order_by($aColumns[$iOrder[0]['column']], strtoupper($iOrder[0]['dir']));
}
} else {
$this->CI->db->order_by($aColumns[0], 'ASC');
}
// Paging
if (isset($iStart) && $iLength != '-1') {
$this->CI->db->limit($iLength, $iStart);
} else {
$this->CI->db->limit(25, 1);
}
$queryResult = $this->CI->db->get($aTable);
// JSON enconding
$json = json_encode(
array(
"draw" => isset($iDraw) ? $iDraw : 1,
"recordsTotal" => $recordsTotal,
"recordsFiltered" => $recordsFiltered,
"data" => $queryResult->result(),
)
);
return $json;
}
public function countAllWhere($aTable = '', $where = [])
{
$this->CI->db->select('COUNT(*) AS `numrows`');
$this->CI->db->where($where);
$query = $this->CI->db->get($aTable);
return $query->row()->numrows;
}
}
<link rel="stylesheet" href="public/js/dataTables1.11.3/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="public/js/dataTables1.11.3/css/select.dataTables.min.css" />
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>
<button style="border: none; background: transparent; font-size: 14px;" id="MyTableCheckAllButton">
<!-- <i class="far fa-square"></i> -->
<i class="showsquare"></i>
</button>
</th>
<th>File name</th>
<th>File size (Kb)</th>
<th>File type</th>
<th>Last modified</th>
<th>Owner</th>
<th>URL</th>
</tr>
</thead>
</table>
<div class="f-event">
<button id="deleteFile" class="delete-file">Delete</button>
</div>
<script src="public/js/dataTables1.11.3/js/jquery.dataTables.min.js"></script>
<script src="public/js/dataTables1.11.3/js/dataTables.select.min.js"></script>
html, body { background: #ebebeb; font-size: 10px; font-family: Verdana; margin: 0; padding: 0; } #container { min-width: 320px; margin: 0px auto 0 auto; background: white; border-radius: 0px; padding: 0px; overflow: hidden; } #tree { float: left; min-width: 319px; border-right: 1px solid silver; overflow: auto; padding: 0px 0; } #data { margin-left: 320px; } #data textarea { margin: 0; padding: 0; height: 100%; width: 100%; border: 0; background: white; display: block; line-height: 18px; } #data, #code { font: normal normal normal 12px/18px 'Consolas', monospace !important; } .content.default { line-height: inherit !important; display: flex; overflow: auto; } .content.default>div { clear: both; /* position: absolute; */ width: 100%; /* max-width: 1200px; */ padding: 10px; } .f-event button { float: right; padding: 5px; margin-top: 10px; border: black; color: black; background: #0000ff26; padding: 8px; } .f-add button { float: right; padding: 5px; margin-bottom: 10px; background: #0000ff26; border: black; color: black; padding: 8px; } td .btn { text-decoration: underline; color: #0f0fdf; } .dataTables_wrapper .dataTables_processing { display: block; background: #0000002e; height: 100% !important; top: 15px; color: white; font-weight: bold; font-size: 26px; } .dataTables_wrapper a:active { background-color: #EA7601; } th.select-checkbox .far { color: #0c0c0c; } th.select-checkbox { text-align: center; } .d-none { display: none; } tr td:nth-of-type(4){ text-transform: uppercase; } tr th{ text-transform: capitalize; } .showsquare:before { content: " "; /* margin-top: -6px; margin-left: -6px; */ border: 1px solid black; border-radius: 3px; width: 12px; height: 12px; display: grid; } .showsquare-full:after { content: "✓"; font-size: 14px; margin-top: -19px; margin-left: -6px; text-align: center; text-shadow: 1px 1px #b0bed9, -1px -1px #b0bed9, 1px -1px #b0bed9, -1px 1px #b0bed9; position: absolute; top: 53px; color: black; left: 32px; } .showsquare-nofull:after { font-size: 14px; margin-top: -19px; margin-left: -6px; text-align: center; text-shadow: 1px 1px #b0bed9, -1px -1px #b0bed9, 1px -1px #b0bed9, -1px 1px #b0bed9; position: absolute; top: 54px; color: black; left: 35px; content: "-"; } .dataTables_info{ top: -6px; position: relative; right: -10px; } .dataTables_length >label{ float: left; } .dataTables_length{ display: flex; }
var myDataTable;
jQuery(document).ready(function() {
myDataTable = jQuery('#example').DataTable({
"processing": true,
rowId: 'id',
search: {
return: true
},
"serverSide": true,
"lengthMenu": [10, 20, 30, 50, 100, 200, 500],
"ajax": {
"url": glb_base_url + 'search_datatable',
"type": 'POST',
"data": function(d) {
d.folder_id = id_folder_selected;
},
error: function(xhr, error, thrown) {
console.log(xhr, error)
alert('Error: lost connect try to reload browser.');
location.reload();
}
},
columns: [{
data: null,
"defaultContent": ""
},
{
data: "name"
},
{
data: "file_size"
},
{
"defaultContent": ""
},
{
data: "create_at"
},
{
data: "create_by"
}
],
'columnDefs': [{
'orderable': false,
searchable: false,
'targets': 0,
'className': 'select-checkbox',
"width": "10px",
},
{
"targets": 2,
"width": "100px"
},
{
searchable: false,
'targets': 3,
"data": function(row, type, val, meta) {
var str = row.file_type + ' FILE';
return str
},
"width": "66px",
},
{
"targets": 4,
"width": "120px"
},
{
"targets": 5,
"width": "120px"
},
{
searchable: false,
'orderable': false,
'targets': 6,
"data": function(row, type, val, meta) {
return '<a class="btn" href="javascript:void(0)" onclick="copyEvent(&#39;' + row.name + '&#39;)">Copy URL</a>&nbsp;&nbsp;<a class="btn" href="javascript:void(0)" onClick="openLink(&#39;' + row.name + '&#39;)">View</a>'
},
"width": "100px",
},
],
'select': {
'style': 'multi',
selector: 'td:first-child'
},
order: [
[1, 'asc']
],
"initComplete": function(settings, json) {
jQuery('#example_info').appendTo('#example_length');
jQuery('#example_filter').prepend(jQuery('.f-event'));
jQuery('.f-event').removeClass('d-none');
}
});
myDataTable.on("click", "th.select-checkbox", function() {
if (jQuery("th.select-checkbox").hasClass("selected")) {
myDataTable.rows().deselect();
jQuery("th.select-checkbox").removeClass("selected");
} else {
myDataTable.rows().select();
jQuery("th.select-checkbox").addClass("selected");
}
}).on("select deselect", function() {
if (myDataTable.rows({
selected: true
}).count() !== myDataTable.rows().count()) {
jQuery("th.select-checkbox").removeClass("selected");
} else {
jQuery("th.select-checkbox").addClass("selected");
}
});
jQuery('#data').on('click', '#deleteFile', function() {
deleteFiles();
})
});
function getSelectedIds() {
return myDataTable.rows({
selected: true
}).ids().toArray();
}
function deleteFiles() {
var ids = getSelectedIds();
if (ids.length <= 0) {
alert('Please select file to delete')
return;
}
var result = confirm("Do You Want to delete?");
if (result) {
jQuery.post('<?php echo base_url('deleteFile') ?>', {
ids: ids,
}, function(data) {}, "json")
.done(function(d) {
if (d.status === false) {
alert(d.message);
}
myDataTable.ajax.reload();
jQuery("th.select-checkbox").removeClass("selected");
})
.fail(function() {
alert('Something Not Right, Can try reload browser');
myDataTable.ajax.reload();
jQuery("th.select-checkbox").removeClass("selected");
});
}
}
function getLinkFromFile(fileName) {
var ulr = glb_base_url.replace("admin/", "");
var part_url = ulr + id_folder_path + '/';
var link = part_url + fileName;
return link;
}
function copyEvent(fileName) {
copyText(getLinkFromFile(fileName));
}
function openLink(fileName) {
window.open(getLinkFromFile(fileName));
}
function copyText(text) {
var input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
var result = document.execCommand('copy');
document.body.removeChild(input);
return result;
}
function callChangeNodeSelected() {
myDataTable.ajax.reload();
jQuery("th.select-checkbox").removeClass("selected");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment