Datatables: Using row grouping, how do I get the count of each grouped row?
I am using Datatables to create gridded data. I managed to group the table using my first column.
I want to do a count for each grouped row and write out the invoice in my grouped row, how would I do that?
If you see the link below, they have a colored grouped row. I would like the graph to appear immediately after the grouped text text.
http://www.datatables.net/examples/advanced_init/row_grouping.html
Thank.
source to share
Using the example you linked marked my comments with //:
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(2, {page:'current'} ).data().each( function ( group, i ) {
//Create vars with each element you want to sum here
if ( last !== group ) {
$(rows).eq( i ).before(
//Get row data here, sum it in vars to display
'<tr class="sum group"><td>'+SumCol1+'</td><td>'+SumCol2+'</td>
//End sum row
'<tr class="group"><td colspan="5">'+group+'</td></tr>'
);
last = group;
//Don't forget to clear your sum vars at the end of each loop!
}
} );
}
source to share
This can be achieved by adding a for loop inside the drawCallBack function. Link to http://www.datatables.net/examples/advanced_init/row_grouping.html for drawCallBack function. Please note that I am using the deprecated dataTable function i.e. FnDrawCallBack replaced it with its latest equivalent.
fnDrawCallback: function(settings) {
var api = this.api();
var rows = api.rows({ page: "current" }).nodes();
var last = null;
var storedIndexArray = [];
api.column(0, { page: "current" })
.data()
.each((group, i) => {
if (last !== group) {
storedIndexArray.push(i);
$(rows)
.eq(i)
.before(
'<tr class="group"><td colspan="4">' +
group +
"<span class='group-count'></span></td></tr>"
);
last = group;
}
});
storedIndexArray.push(
api.column(0, { page: "current" }).data().length
);
for (let i = 0; i < storedIndexArray.length - 1; i++) {
let element = $(".group-count")[i];
$(element).text(
storedIndexArray[i + 1] - storedIndexArray[i]
);
}
}
source to share