Print child rows
Print child rows
Sorry for the poor English (i'm using translator) and also for the code; I still have some difficulties with JS and I’ve been using ChatGPT to help.
But I needed a new solution to print child rows in DataTables 2.x.
I arrived at this result, which seems to work, and I wanted to share it here as a tip in few steps:
- Create a format function
The parameter d represents the row’s data:
function format(d) {
return 'Extra: ' + Math.random().toFixed(6);
}
- Add a print button in the layout
Use the format function to generate content for each row:
buttons: [
{
key: 'print',
extend: 'print',
className: 'btn btn-sm btn-secondary',
exportOptions: { columns: ':visible' },
customize: function (win, conf, api) {
api.rows().every(function () {
var extra = format(this.data());
if (!extra) return;
$(this.node()).after(
'<tr>' +
'<td colspan="100%" style="padding:3px 6px; border-bottom:2px solid #ddd;">' +
extra +
'</td>' +
'</tr>'
);
});
}
}
]
- Initialize click events for showing/hiding child rows
table.on('click', 'tbody td.dt-control', function () {
var row = table.row($(this).closest('tr'));
var extra = getDetails(row.data());
if (row.child.isShown()) {
row.child.hide();
} else {
row.child(extra).show();
}
});
Replies
Excellent! Many thanks for sharing this with us
.
Allan