Column rendering in dynamically generate table
Column rendering in dynamically generate table
Khalid Teli
Posts: 251Questions: 71Answers: 0
Hi @allan
Happy New Year!
I am populating the table dynamically using
function getDT(filter_supplierref) {
var columns = [];
var fields = [];
$.ajax({
url: "/xxxxxxxxx_fetch.php",
type:'POST',
data: {filter_supplierref: JSON.stringify(filter_supplierref)},
success: function (data) {
data = JSON.parse(data);
columnNames = Object.keys(data.data[0]);
for (var i in columnNames) {
columns.push({data: columnNames[i],
title: capitalizeFirstLetter('<div><span>'+columnNames[i]+'</span></div>')})
}
if ( $.fn.dataTable.isDataTable( '#contracts_forecast' ) ) {
$('#contracts_forecast').DataTable().clear();
$('#contracts_forecast').DataTable().destroy();
$('#contracts_forecast tbody').empty();
$('#contracts_forecast thead').empty();
}
var table = $('#contracts_forecast').DataTable({
"processing": true,
"serverSide": true,
"paging": true,
"lengthMenu": [ [10, 25, 50, 500], [10, 25, 50, 500] ],
data: data.data,
columns: columns,
"ajax":
{
url: "/xxxxxxfetch.php",
type:'POST',
data: {filter_supplierref: JSON.stringify(filter_supplierref)}
},
dom: "Brtlip",
//destroy: true,
select: true,
//retrieve:true,
buttons: [
'excelHtml5',
'csvHtml5',
],
"columnDefs": [
]
} );
} });}
$('#filter').click(function(){
filter_supplierref = $('#filter_supplierref').val();
$(document).ready(function() {
getDT(filter_supplierref);
} );
});
The no. of columns change based on the filter data.
Is there a possibility to add a rendered column to the table , Like we do normally
{ data: null, render: function (data, type, row){
if (n1 !== n ) {
var diff = (parseFloat(data.Total_ThisYear - data.Total_LastYear) / data.Total_LastYear)*100;
return parseFloat(diff).toFixed(2) + '%';}
else{
var diff = ((data.Total_ThisYear - data.Total_LastYear_ToDate) / data.Total_LastYear_ToDate)*100;
return parseFloat(diff).toFixed(2) + '%';} }
else{ return 0;}
}
Thank you
Answers
You can use
columnDefs
. You should also be able to add it dynamically in thesuccess
function - you will need to determine when to add it depending on where you want the column. Have you tried? What issues do you have?If you have problems please post a link to your page or a test case replicating the issue so we can help debug.
https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case
Kevin
You could use Javascript splice() to insert the rendered column where required into the
columns
array in thesuccess
function.Kevin
@kthorngren
Thank you very much.
I managed to add the headers insid esuccess function using:
and then render the data using
Thank you.
As always appreciate your help.