I have a Datatable (Boostrap4), where I need edit and delete links for each row. What I'm having trouble figuring out is how to dynamically create those links based on user. I need the edit and delete links to only appear for the currently logged in users own items (and no one elses), if possible.
I know I can wrap the 'defaultContent' line with PHP tags and perform logic. What I'm missing is if there's any way to compare (say) the First and Last name to see if that person matches the logged in user to control what items have the edit/delete links.
aoColumns: [
{ mData: 'first_name' } ,
{ mData: 'last_name' },
{ mData: 'note' },
{
data: null,
className: "left",
defaultContent: '<a style="display:inline-block;" href="edit.php" class="editor_edit">Edit</a> / <a href="delete.php" class="editor_remove">Delete</a>'
}
]
If your Edit/Delete links allow user to modify back end data, you're going to need to authenticate the user server side before committing the changes anyways.
For the time being, as you need to offer possibility to modify owned data to authorized users, you may produce individual user-based data to feed DataTable, so that there will be editable
flag for each row set/unset, based on user's permission.
Upon that, you may use columns.render
option to render or not Edit//Delete links.
Following example, demonstrates that approach:
//data supplied to DataTables, with 'editable' property
//dependant on user permissions, checked server-side
const srcData = [
{fname: 'Steve', lname: 'Rogers', note: '', editable: true},
{fname: 'Anthony', lname: 'Stark', note: '', editable: false},
{fname: 'Peter', lname: 'Parker', note: '', editable: true},
{fname: 'Thor', lname: 'Odinsson', note: '', editable: false},
];
//DataTables initialization with fourth column rendered
//as 'Edit/Delete' links visible for editable rows only
const dataTable = $('#mytable').DataTable({
dom: 't',
data: srcData,
columns: [
{title: 'First Name', data: 'fname'},
{title: 'Last Name', data: 'lname'},
{title: 'Note', data: 'note'},
{title: '', data: null, render: (data, type, row, meta) => row.editable ? '<a style="display:inline-block;" href="edit.php" class="editor_edit">Edit</a> / <a href="delete.php" class="editor_remove">Delete</a>' : ''}
]
});
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="mytable"></table>
</body>
</html>
</div>