Two targets for the same column datatable - javascript

I have a datatable with json ajax.
But, i need to pass for the same column two targets. How i do that?
"columns": [
{ "data": "tpPedido" },
{ "data": "os" },
{ "data": "userMobile.nome" },
{ "data": "produto.nmProduto" },
{ "data": "status.NmStatus" },
{ "data": "produto.garantia.descricao" },
{ "data": "valor" },
{ "data": "valoradiantado" },
{ "data": "idPedidoAssistencia" },
{ "data": "idPedidoAssistencia" }
],
And the columndefs i trying to do this:
{ "render": function ( data, type, row ) {
return '<a onclick="relatorioAcerto('+data+')">R$: ' + parseFloat(data).toFixed(2).replace('.', ',').replace(/(\d)(?=(\d{3})+\,)/g, "$1." + '</a>');
}, "targets": 6,9},

You can define directly in columns array. render function accept three parameters. The last parameter holds entire data object.
"columns": [
{ "data": "tpPedido" },
{ "data": "os" },
{ "data": "userMobile.nome" },
{ "data": "produto.nmProduto" },
{ "data": "status.NmStatus" },
{ "data": "produto.garantia.descricao" },
{
"data": null,
"render" : function (data, type, row) {
return '<a href="'+row.idPedidoAssistencia+'" >Click here</a>';
}
},
{ "data": "valoradiantado" },
{ "data": "idPedidoAssistencia" },
{
"data": null,
"render" : function (data, type, row) {
return '<a href="'+row.idPedidoAssistencia+'" >Click here</a>';
}
}
],

Related

How to pass request body data in type POST using Datatable for Serverside pagination using Javascript

I am trying to implement ServerSide pagination using Datatable for AJAX POST request
here is my Javascript Code, if I use JSON.stringify for data field then api won't hit
$('#tripboard_table').DataTable({
proccessing: true,
serverSide: true,
ajax: {
"url": "http://localhost:5000/api/v1/trip/get-trip-list",
"contentType": "application/json; charset=utf-8",
"type": "POST",
"dataType": "json",
"data": {
"driver_id": "",
"franchise_id": login_data.franchise_id,
"page_no": 0,
"page_size": 10
}
},
columns: [
{ "data": "" },
{ "data": "reference_number" },
{ "data": "consignor_name" },
{ "data": "consignee_name" },
{ "data": "from_city" },
{ "data": "to_city" },
{ "data": "status" },
{ "data": "route_name" },
{ "data": "vehicle_number" },
{ "data": "driver_name" },
{ "data": "pickup_date" },
{ "data": "scheduled_delivery_date" },
{ "data": "total_money_allocated" },
{ "data": "total_money_released" }
]
});
if we remove JSON.stringify function from data and passed data as it is then api gets hit and showing error alert that
DataTables warning: table id=tripboard_table - Ajax error. For more
information about this error, please see http://datatables.net/tn/7
and no data is inserted in table.
In console it shows
Method Not Allowed
The method is not allowed for the requested URL.
Please suggest solution for this..
Use this for adding to existing request of data table
function (d) {
d.driver_id = "";
d.franchise_id = login_data.franchise_id;
d.page_no = 0;
d.page_size = 10;
return d;
}
https://datatables.net/manual/server-side#Sent-parameters
$('#tripboard_table').DataTable({
proccessing: true,
serverSide: true,
ajax: {
"url": "http://localhost:5000/api/v1/trip/get-trip-list",
"contentType": "application/json; charset=utf-8",
"type": "POST",
"dataType": "json",
"data": function (d) {
d.driver_id = "";
d.franchise_id = login_data.franchise_id;
d.page_no = 0;
d.page_size = 10;
return JSON.stringify(d)
});
}
},
columns: [
{ "data": "" },
{ "data": "reference_number" },
{ "data": "consignor_name" },
{ "data": "consignee_name" },
{ "data": "from_city" },
{ "data": "to_city" },
{ "data": "status" },
{ "data": "route_name" },
{ "data": "vehicle_number" },
{ "data": "driver_name" },
{ "data": "pickup_date" },
{ "data": "scheduled_delivery_date" },
{ "data": "total_money_allocated" },
{ "data": "total_money_released" }
]
});

How to conditionally draw DataTables columns in Razor pages

Currently we are doing this to draw the columns for a server side DataTable for 2 different users, we were able to hide the column headers using razor code to only draw them when the user is an admin or group admin. However when it comes to drawing the data we are having an issue with the following:
function getTableColumns() {
var allowedToDelete = #(User.IsInRole("SysAdmin") || GroupManager.IsUserGroupAdmin(Model.GroupId, User.FindFirst(ClaimTypes.NameIdentifier).Value) ? "true" : "false");
if (allowedToDelete) {
return [{ "defaultContent": "" },
{ "data": "deadlineDate", "name": "DeadlineDate" },
{ "data": "priority", "name": "Priority" },
{ "data": "jobNumber", "name": "JobNumber" },
{ "data": "project", "name": "Project" },
{ "data": "description", "name": "Description" },
{ "data": "reference", "name": "Reference" },
{ "data": "subReference", "name": "SubReference" },
{ "data": "employee", "name": "Employee" },
{ "data": "allocatedTo", "name": "AllocatedTo" },
{
"render": function (data, type, full, meta) {
return "<i title ='Archive Item' class='fa fa-archive table-icon-view' onclick='archiveJob(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
},
{
"render": function (data, type, full, meta) {
return "<i title ='Edit' class='fa fa-pencil table-icon-edit' onclick='editJob(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
},
{
"render": function (data, type, full, meta) {
return "<i title ='Delete' class='fa fa-trash table-icon-delete' onclick='showDeleteModal(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
},
{ "data": "issueDate" },
{ "data": "startDate" },
{ "data": "createdBy" },
{ "data": "createdDate" },
{ "data": "notes" }];
} else {
return [{ "defaultContent": "" },
{ "data": "deadlineDate", "name": "DeadlineDate" },
{ "data": "priority", "name": "Priority" },
{ "data": "jobNumber", "name": "JobNumber" },
{ "data": "project", "name": "Project" },
{ "data": "description", "name": "Description" },
{ "data": "reference", "name": "Reference" },
{ "data": "subReference", "name": "SubReference" },
{ "data": "employee", "name": "Employee" },
{ "data": "allocatedTo", "name": "AllocatedTo" },
{
"render": function (data, type, full, meta) {
return "<i title ='Edit' class='fa fa-pencil table-icon-edit' onclick='editJob(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
},
{ "data": "issueDate" },
{ "data": "startDate" },
{ "data": "createdBy" },
{ "data": "createdDate" },
{ "data": "notes" }];
}
}
Is there a way to optimise this so that we don't have to repeat the code just to hide 2 icon links?
You could use the columns.visible option to display/hide the column accordingly.
Additionally, it might be worth looking at Reusable renderers to avoid some of the repetition with the rendering functions.
Creating such a rendering function may look like this:
$.fn.dataTable.render.icon = function ( title, icon, func) {
return function ( data, type, row ) {
return "<i title ='" + title + "' class='fa " + icon + "' onclick='" + func + "(\""
+ row.groupId + "\",\"" + row.id + "\")'></i>";
}
};
You could then use this as follows:
{
//Column visibility
visible: allowedToDelete,
//Reusable renderer
render: $.fn.dataTable.render.icon('Archive Item', 'fa-archive table-icon-view', 'archiveJob')
},
{
visible: allowedToDelete,
render: $.fn.dataTable.render.icon('Edit', 'fa-pencil table-icon-edit', 'editJob')
},
{
visible: allowedToDelete,
render: $.fn.dataTable.render.icon('Delete', 'fa-trash table-icon-delete', 'showDeleteModal')
},
You could have the default array be defined in a variable, and push the 2 icon links into it inside the if, before returning:
function getTableColumns() {
var allowedToDelete = #(User.IsInRole("SysAdmin") || GroupManager.IsUserGroupAdmin(Model.GroupId, User.FindFirst(ClaimTypes.NameIdentifier).Value) ? "true" : "false");
var dataArray = [{ "defaultContent": "" },
{ "data": "deadlineDate", "name": "DeadlineDate" },
{ "data": "priority", "name": "Priority" },
{ "data": "jobNumber", "name": "JobNumber" },
{ "data": "project", "name": "Project" },
{ "data": "description", "name": "Description" },
{ "data": "reference", "name": "Reference" },
{ "data": "subReference", "name": "SubReference" },
{ "data": "employee", "name": "Employee" },
{ "data": "allocatedTo", "name": "AllocatedTo" },
{
"render": function (data, type, full, meta) {
return "<i title ='Edit' class='fa fa-pencil table-icon-edit' onclick='editJob(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
},
{ "data": "issueDate" },
{ "data": "startDate" },
{ "data": "createdBy" },
{ "data": "createdDate" },
{ "data": "notes" }];
if (allowedToDelete) {
return dataArray.Concat([{
"render": function (data, type, full, meta) {
return "<i title ='Edit' class='fa fa-pencil table-icon-edit' onclick='editJob(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
},
{
"render": function (data, type, full, meta) {
return "<i title ='Delete' class='fa fa-trash table-icon-delete' onclick='showDeleteModal(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
}]).ToArray();
} else {
return dataArray;
}
}

How to map an indexed array data source in DataTables

Say i have an array as the data source for DataTables, delivered through AJAX
{
"data": [
[
"https://stackoverflow.com/questions/ask",
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
]
]
}
I want to ignore the first cell and not output it as a column, so how can i map the indexed data to the columns? I have already tried this, but it gives an error:
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "data/objects.txt",
"columns": [
{ "data": [1] },
{ "data": [2] },
{ "data": [3] },
{ "data": [4] },
{ "data": [5] },
{ "data": [6] }
]
} );
} );
Uncaught TypeError: Cannot read property 'mData' of undefined
I also tried to reference the indexes like this
"data": 1
Doesn't work either.
If the source was an Object with keys, referencing would work like this:
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
I managed to find a solution myself, this code will make the first cell invisible and display the other cells:
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "data/objects.txt",
"columnDefs": [
{ "targets": [0], "visible": false },
{ "targets": '_all', "visible": true }
]
} );
} );
var obj = {}
var keys = ['name', 'job', 'location', 'number', 'date', 'salary']
var arr = [
'https://stackoverflow.com/questions/ask',
'Tiger Nixon',
'System Architect',
'Edinburgh',
'5421',
'2011/04/25',
'$120000'
]
.filter((item, i) => !!i)
.forEach((v, i) => obj[keys[i]] = v)
console.log(obj)

How can I show Base64 image in a server-side DataTable?

This is my HTML for server side data to load the data into the table of the data get data from controller
<script type="text/template" id="tablescript">
<td><%=Name%></td>
<td><%=PhoneNumber%></td>
<td><%=CNIC%></td>
<td><%=So%></td>
<td><%=Thumb%></td>
<td><%=Image%></td>
<td><%=NomineeImage%></td>
<td>
<i class="fa fa-pencil-square-o" aria-hidden="true" onclick="editMember('<%= Id%>')" style="cursor:pointer;font-size: 20px;"></i>
<span class="fa fa-trash" aria-hidden="true" style="cursor:pointer;color:red;font-size: 20px;" onclick="deleteMember('<%= Id%>')"></span>
<span class="fa fa-ban" aria-hidden="true" style="cursor:pointer;color:red;font-size: 20px;" onclick="blockMember('<%= Id%>')"></span>
<span class="fa fa-check" aria-hidden="true" style="cursor:pointer;color:green;font-size: 20px;" onclick="activeMember('<%= Id%>')"></span>
</td>
</script>
<table class="table table-hover table-bordered table-striped" id="tblloaddata"></table>
Ajax Request go to the mvc controller and get the list was load to model but not show my datatable.
var table;
var loadtable = function () {
var getUrl = $("#hidLoadMembersUrl").val();
var tmpl = _.template($("#tablescript").html());
table = $("#tblloaddata").DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: getUrl,
type: "POST"
},
"columns": [
{ "data": "Name", "title": "Name" },
{ "data": "PhoneNumber", "title": "PhoneNumber" },
{ "data": "CNIC", "title": "CNIC" },
{ "data": "So", "title": "SoDoWoName" },
{ "data": "Thumb", "title": "Thumb" },
{ "data": "Image", "title": "Image" },
{ "data": "NomineeImage", "title": "NomineeImage" },
{ "data": null, "title": "Action", "orderable": "false" },
],
"rowCallback": function (row, data) {
console.log(data);
$(row).html(tmpl(data));
}
});
};
You should use render property to display images;
table = $("#tblloaddata").DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: getUrl,
type: "POST"
},
"columns": [
{ "data": "Name", "title": "Name" },
{ "data": "PhoneNumber", "title": "PhoneNumber" },
{ "data": "CNIC", "title": "CNIC" },
{ "data": "So", "title": "SoDoWoName" },
{ "data": "Thumb", "title": "Thumb" },
{ "data": "Image", "title": "Image", render : function (data, type, full, meta)
{ return '<img src="'+data.Image+'"/>'; }
},
{ "data": "NomineeImage", "title": "NomineeImage" },
{ "data": null, "title": "Action", "orderable": "false" },
],
"rowCallback": function (row, data) {
console.log(data);
$(row).html(tmpl(data));
}
});

how to add button in data table so , that the particular column can be edited

$(document).ready(function() {
$('#example').dataTable( {
//"ajax": "jsonArray.txt",
"ajax" :{
"url" : "jsonArray.txt",
"dataSrc" :"caseList"
},
"columns": [
{ "data": "caseId" },
{ "data": "accountId" },
{ "data": "createdBy" },
{ "data": "caseCreationDate" },
{ "data": "serialNo" },
{ "data": "productLine" },
{ "data": "caseStatus" },
{ "data": "description" }
],
"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
var addButton = '<a name="caseid" data-PLName="'+aData["plShortName"]+'" data-caseId="'+aData["caseId"]+'" class="caseNo">'+aData["caseId"]+'</a>';
$('td:eq(0)', nRow).html(addButton);
}
} );
} );
This, is the piece of code which i have written for the data table,Its not working for me..kindly tell me where the problem is. and the right way to write this code.
you cant not directly write your ajax call instead use datatable "sAjaxSource": url attribute, or use oSettings.jqXHR to write your custom ajax call
oSettings.jqXHR = $.ajax({
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
});

Categories

Resources