different columnDefs for multiple tables
different columnDefs for multiple tables
zehgeh
Posts: 7Questions: 2Answers: 0
Hello, I want to have different columnDefs for several tables. Unfortunately, this only works for a single table. But not with several tables. I have a standard function for all dynamic tables:
$('.table-ajax').each((i, el) => {
const tableCells = [];
$(el).find('th').each((i, element) => {
if (typeof $(element).data('id') !== 'undefined') {
let $colName = $(element).data('id');
if ($colName === '') $colName = 'default';
tableCells.push({ data: $(element).data('id'), className: `col-${$colName.toLowerCase()}` });
}
});
const table = $(el)
.DataTable({
processing: false,
serverSide: false,
destroy: true,
deferRender: true,
order: [],
ajax: ajaxConnectionConfigurator.getAjaxRequest(el),
columns: tableCells,
});
table.columns.adjust().draw();
});
And for the respective, specific table I then try it like this. And this works:
if ($('table#users').length > 0) {
$.extend($.fn.dataTable.defaults, {
columnDefs: [
{
defaultContent: '-',
targets: '_all',
},
{
targets: 1,
render(data, type, row) {
return `${row['lastname']}, ${row['firstname']}`;
},
},
{
targets: [4],
render(data) {
return $.map(data, (d) => d.value).join(', ');
},
},
{
targets: 5,
orderable: false,
}],
});
}
But if I take another table now, it won't work.
if ($('table#supplierconditions').length > 0) {
$.extend($.fn.dataTable.defaults, {
columnDefs: [
{
defaultContent: '-',
targets: '_all',
},
{
targets: 4,
orderable: false,
render() {
return '<i class="material-icons edit"></i>';
},
},
],
});
}
This discussion has been closed.
Answers
The $.fn.dataTable.defaults object is to set the defaults for all the Datatables on the page. I don't think it is meant to work the way it looks like you are trying to use it.
I would look at creating a function with all your columnDefs configs. In your loop in the first code snippet call the function passing the ID of the table then the function can return the columnDefs.
Kevin
Ok thanks, it works now.