I have to hide some columns of my datatable if the user isn't ADMIN. In HTML I have this code
<table id="fleetsTable"
class="table table-bordered table-striped">
<thead>
<tr>
<th>Application</th>
<th>Cubic</th>
<th>Power</th>
<th>Euro class</th>
<th>Engine Type</th>
<th>Traction</th>
<th>Transmission</th>
<th>Cars</th>
<th sec:authorize="hasRole('ROLE_ADMIN')">Delete</th>
</tr>
</thead>
</table>
The table is filled with ajax value through javascript. I have this code:
if ( ! $.fn.DataTable.isDataTable( '#fleetsTable' ) ) {
fleetTable = $('#fleetsTable').DataTable({
responsive: true,
//disable order and search on column
columnDefs: [
{
targets: [7, 8],
orderable: false,
searchable: false,
}
],
//fix problem with responsive table
"autoWidth": false,
"ajax": "fleet/table",
"columns": [
{ "data": "application" },
{ "data": "cubic" },
{ "data": "power" },
{ "data": "euroClass" },
{ "data": "engineType" },
{ "data": "traction" },
{ "data": "transmission" },
{
data:null, render: function ( data, type, row ) {
return '<button type="button" class="btn btn-primary" id="showCarsButton">Show cars</button>';
}
},
{data:null, render: function ( data, type, row ) {
return '<button type="button" class="btn btn-danger" id="deleteFleet" data-toggle="modal"'
+'data-target="#deleteFleetModal">Delete</button>'
}
}
],
});
}
else {
fleetTable.ajax.url("table").load();
}
To check if user has the right role I use a hidden input in my HTML and
document.getElementById("role").value=="[ROLE_ADMIN]"
in javascript. But how can I avoid to build the delete button? The html code only hide the name of the column. Thanks
UPDATE: for now I hide the column
if (!(document.getElementById("role").value=="[ROLE_ADMIN]")){
// Get the column API object
var column = fleetTable.column(8);
// Toggle the visibility
column.visible( false);
}
but I prefer to don't create the column
Very simple. You can use columnDef
's visible
property :
columnDefs : [
{ targets: 8, visible: document.getElementById('role').value == '[ROLE_ADMIN]' }
]
...Assuming it is column #8 we want to skip - by that the column is never created if #role
is any different from [ROLE_ADMIN]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With