Reputation: 13162
In my application there are some columns that were given privileges. If the column is not given the right to access that particular column is not shown.
My code is like this : http://jsfiddle.net/oscar11/5jccbzdy/11/
// DataTable
var table = $('#example').DataTable({
"order": [[0, 'asc']],
"drawCallback": function (settings){
var api = this.api();
// Zero-based index of the column containing names
var col_name = 0;
// If ordered by column containing names
if (api.order()[0][0] === col_name) {
var rows = api.rows({ page: 'current' }).nodes();
var group_last = null;
api.column(col_name, { page: 'current' }).data().each(function (name, index){
var group = name;
var data = api.row(rows[index]).data();
if (group_last !== group) {
$(rows[index]).before(
'<tr class="group" style="background-color:' + data[4] + '"><td colspan="5">' + group + '</td></tr>'
);
group_last = group;
}
});
}
}
});
How to make the above code becomes more dynamic and adjusting the number of columns that are given privileges?
If the number of columns that were given privileges: 5, then:
'<tr class="group" style="background-color:' + data[4] + '"><td colspan="5">' + group + '</td></tr>'
If the number of columns that were given privileges: 3, then:
'<tr class="group" style="background-color:' + data[2] + '"><td colspan="3">' + group + '</td></tr>'
Thank you
Upvotes: 0
Views: 1752
Reputation: 58860
SOLUTION
You can use columns.name
option to define a name for data column containing color.
Then in the row grouping code you can use column-selector
color:name
in api.column("color:name").index()
to get index of that column.
Use the code below:
// DataTable
var table = $('#example').DataTable({
"order": [[3, 'asc']],
"columnDefs": [
{ targets: 3, name: "group" },
{ targets: -1, name: "color" }
],
"drawCallback": function (settings){
var api = this.api();
// Zero-based index of the column containing group names
var col_name = api.column("group:name").index();
var col_color = api.column("color:name").index();
// If ordered by column containing names
if (api.order()[0][0] === col_name) {
var rows = api.rows({ page: 'current' }).nodes();
var group_last = null;
api.column(col_name, { page: 'current' }).data().each(function (group, index){
if (group_last !== group){
var color = api.cell({
row: api.row(rows[index]).index(),
column: col_color
}).data();
$(rows[index]).before(
'<tr class="group" style="background-color:' + color + '"><td colspan="5">' + group + '</td></tr>'
);
group_last = group;
}
});
}
}
});
DEMO
See this jsFiddle for code and demonstration.
Upvotes: 1