Datatable row grouping - javascript

I have a working datatable that is retrieving data from a file :
I want to group row, something like this :
https://datatables.net/examples/advanced_init/row_grouping.html
My goal would to have my datatable to look like this, grouping row by the date (last column), but even looking at the code, I have trouble to make it work. I'd like some help to make that work if you could.
Here is the code of my datatable :
$(document).ready(function() {
$('#datatable').DataTable( {
"ajax": "<?php echo base_url()."assets/files/data/data.txt"; ?>" ,
"columns": [
{ "data": "etat" },
{ "data": "dest" },
{ "data": "message" },
{ "data": "exp" },
{ "data": "date" }
],
"order": [[ 0, "desc" ]],
"responsive": true
} );
} );

You should use drawCallback function.
Try.
$(document).ready(function() {
$('#datatable').DataTable({
"columns": [
{ "data": "etat" },
{ "data": "dest" },
{ "data": "message" },
{ "data": "exp" },
{ "data": "date" },
{ "data": "extra" }
],
"order": [[ 4, "desc" ]],
"responsive": true,
drawCallback: function (settings) {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(4, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="8" style="BACKGROUND-COLOR:rgb(237, 208, 0);font-weight:700;color:#006232;">' + 'GRUPO ....' + group + '</td></tr>'
);
last = group;
}
});
}
});
} );
Result: https://jsfiddle.net/cmedina/7kfmyw6x/13/

It seems you get the error when outputting the url by PHP into the Javascript.
Try this instead:
ajax: "<?php echo base_url() . 'assets/files/data/data.txt'; ?>"
Not the single-qoutes in the PHP-code.

Related

DataTables add tag to column based on another attribute's value

I am trying to get the <span> tag into the "salesStatusName" column cell that already has some data in it. The tag should be placed in there when the value of the last column "completelyDelivered" is true. However, I also don't want "completelyDelivered" to even be a column in the table, so I assume I somehow need to access the value of "completelyDelivered" attribute in the received JSON.
How it looks now:
https://i.imgur.com/S171i2o.png circle in a separate column
How I want it to look:
https://i.imgur.com/74nCnGu.png circle within Status Name column
I looked around and there are very similar questions, but I was unable to implement any solution.
DataTables instantiation code:
Note that I use AJAX and get JSON code returned
$(document).ready(function () {
$.fn.dataTable.moment('MM-DD-YYYY');
var datatableObj = $('#salesOrdersTable').DataTable({
"ajax": {
"url": "/Orders/GetAll",
"type": "GET",
error: function (error) {
RedirectUserToErrorPage();
}
},
"columns": [
{ "data": "salesOrderNumber" },
{ "data": "salesOrderNumber" },
{ "data": "poNumber" },
{ "data": "orderDateString" },
{ "data": "company" },
{ "data": "salesPerson" },
{ "data": "salesStatusName" },
{ "data": "completelyDelivered" }
],
"columnDefs": [
{
"targets": 0, //salesOrderNumber col
"orderable": false,
"render": function (data) {
return '<input type="button" value="+" onclick="location.href=\'/Shipments/Get?salesOrderNumber=' + data + '\'">';
}
},
{
"targets": 7, //completelyDelivered col
"render": function (data) {
if (String(data) == "true") {
return '<span class="SalesOrderDelivered">⬤</span>';
}
return "";
}
},
{ className: "salesOrderNumber", "targets": 1 },
],
});
I've done some research and figured it out.
Basically, if you write { "data": null }, as a definition for a column, you gain access to all properties of that row. So, in "render": function(data) function, write data["propertyName"] to get the value.
Code:
$(document).ready(function () {
$.fn.dataTable.moment('MM-DD-YYYY');
var datatableObj = $('#salesOrdersTable').DataTable({
"ajax": {
"url": "/Orders/GetAll",
"type": "GET",
error: function (error) {
RedirectUserToErrorPage();
}
},
{"data": "salesOrderNumber",},
{ "data": "salesOrderNumber" },
{ "data": "poNumber" },
{ "data": "orderDateString" },
{ "data": "company" },
{ "data": "salesPerson" },
{ "data": null, },//this is Sales Status column.
//"data: null" accesses all JSON data. We need this so that in "columnDefs" section
//we can use the values of both "completelyDelivered" and "salesStatusName" properties.
],
"columnDefs": [
{
"targets": 0, //button col
"orderable": false,
"render": function (data) {
return '<input type="button" value="+" onclick="location.href=\'/Shipments/GetShipments?salesOrderNumber=' + data + '\'">';
}
},
{
"targets": 6, //Sales Status col.
"render": function (data) { //This is where we can use values of "completelyDelivered" and "salesStatusName" JSON properties.
if (String(data["completelyDelivered"]) == "true") {
return (String(data["salesStatusName"]) + '<span class="AllDelivered"> ⬤</span>');
} else {
return String(data["salesStatusName"]);
}
}
},
{ className: "salesOrderNumber", "targets": 1 },
],
});

Datatable get the values of all rows of a specific column

How to get all values of all rows of a specific column?
Basically what I want to achieve is, get all the values from 'Key' column and push to allAdminKeys array as global variable because I need those values in somewhere else.
var t = $('#adminKeysTable').DataTable( {
"ajax": {
"url": getKeysById,
"dataSrc": function(json) {
var rows = [];
for (var i=0;i<json.keys.length;i++) {
//skip rows "if a condition is met"
//here just any rows except row #1
if (json.keys[i].privileges == '32')
rows.push(json.keys[i]);
}
return rows;
}
},
"columns": [
{ "data": null },
{ "data": "name" },
{ "data": "key" },
{ "data": null }
],
"columnDefs": [
{ "targets": 0, "searchable": false, "orderable": false},
{ "targets": 2, "name": "key"},
{ "targets": -1, "defaultContent": '<div class="tb-btn regenerate-btn" id="btnRegenerateAdminKey" data-toggle="modal" data-target="#regenerateAdminKeyConfirmation"></div>'}
],
"order": [[ 1, 'asc' ]],
"paging": false,
"ordering": false,
"info": false,
'processing': true
} );
var allAdminKeys = [];
var rowData = t.rows().data(); //t is my table
$.each($(rowData), function(key,value){
allAdminKeys.push(value["key"]); //filter by "Key" column
})
console.log(allAdminKeys); // returning an empty array
You can use .columns() function to access the data
let col = 0 // can be column index or css class of column header
// get all cells of the column
const cells = $yourDataTable.columns(col).nodes()
"initComplete": function(settings, json){
for (var i=0;i<json.keys.length;i++) {
allAdminKeys.push(json.keys[i].key);
}
}
Managed to achieve what I wanted by adding this.

datatables with ajax response

How to use java script variable inside blade syntax. (getting error Use of undefined constant buttonID)
The below is the code :
var t = $("#datatable").DataTable({
"order": [[ 1, 'asc' ]],
"ajax": "questions1/get-data",
"deferRender": true,
"processing": true,
sAjaxDataProp: "",
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "description" },
{ "data": "answers.[, ].name" },
{ "data": "campaigns.[, ].name" },
{ "data": "label" },
{
sortable: false,
"render": function ( data, type, full, meta ) {
var buttonID = full.id;
return '#can('view', $question)<span class="glyphicon glyphicon-eye-open" aria-hidden="true"/>#endcan
#can('update', $question)<span class="glyphicon glyphicon-pencil" aria-hidden="true"/>#endcan';
}
}
],
});
Use the code below:
"render": function ( data, type, full, meta ) {
var buttonID = full.id;
#can('view', $question)
return '<span class="glyphicon glyphicon-eye-open" aria-hidden="true"/>';
#endcan
#can('update', $question)
return '<span class="glyphicon glyphicon-pencil" aria-hidden="true"/>';
#endcan
}

Datatables, how to sort a table so a specific row is always the first row?

I got a small question.
My datatable uses AJAX to gather the rows for my table, the table sort on 6th. column.
Is it possible to always have a specific row to be first? No matter how the sorting is gone?
It does not matter if the row change position after the initial sorting.
My code looks like this:
$('#servertable').DataTable( {
"ajax": "/objects.php",
"deferRender": true,
"order": [[ 5, "desc" ]],
"pageLength": 25,
"columns": [
{ "data": "id" },
{
"data": "hostname",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='/"+oData.url+"'>"+oData.hostname+"</a>");
}
},
{ "data": "version" },
{ "data": "country_cn" },
{ "data": "map_id" },
{ "data": "players" }
]
});
I think this is one of the cases, where a custom sorting plugin is in its place. I guess you want to have certain players on top of the list, all the time? If you have an array of player names which should stay on the top :
var players = ['Yuri Berry', 'Vivian Harrell'];
then you can implement a sorting plugin like this :
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"players-on-top-asc": function( a, b ) {
a = ~players.indexOf(a) ? new Array(255).join('a') : a;
return a.localeCompare(b);
},
"players-on-top-desc": function( a, b ) {
a = ~players.indexOf(a) ? new Array(255).join('z') : a;
return b.localeCompare(a);
}
});
usage :
$('#servertable').DataTable( {
...
"columns": [
...
{ "data": "players", type: "players-on-top" }
]
});
see a small demo, look for column #2 -> http://jsfiddle.net/ryfce85u/

Datatables Format for Currency

I need to format a currency using commas in datatables JSON data. But I have got no luck, Please help me.
The code:
listReportByProductCat(function (json) {
var table = $('#bycat_table').DataTable({
"columnDefs": [
{ "visible": false, "targets": 1 }
{ "column": num-fmt, "targets": 3 } // PROBLEM HERE
],
"order": [[ 1, 'asc' ]],
"displayLength": 25,
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(1, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="6"><b>'+group+'</b></td></tr>'
);
last = group;
}
} );
},
destroy: true,
processing: true,
data: json,
"columns": [
{ "data": "Prod ID" },
{ "data": "catname" },
{ "data": "Product Name" },
{ "data": "Price" },
{ "data": "Qty" },
{ "data": "Total" }
]
});
So the problem happened on target : 3, I followed datatables doc using num-fmt but still doesn't work. Please help.
follow this link for sorting formatted data
https://datatables.net/plug-ins/sorting/#formatted_numbers
<script type="text/javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" src="dataTables.numericComma.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable( {
"columnDefs": [
{ "type": "numeric-comma", targets: 3 }
]
} );
} );
</script>

Categories