Reinitialize table with different column set
Reinitialize table with different column set
I have a view switcher i.e. Monthly & Lifetime View. Depend upon the Switcher, The columns in Datatable will change. 4 columns for Monthly View & 3 Columns for Lifetime View. I tried destroying the table and initializing the same data table with the different set of columns but it is not happening though data is refreshing.
Data table Version: 1.10.19
View 1: Monthly View
View 2: Lifetime View
PFB, the code: (Demo of passing columns dynamically)
function initTable( r_filters, option ) {
if ( option=="lifetime" ) {
r_columns = [
{"title": "Contract Code", "data": "contract_code","orderable$
{"title": "Total Revenue (USD)", "orderable":true, "data": "t$
];
extra_data = {'custom_filter':r_filters, "view_type":"lifetime"$
} else if( option == "monthly") {
r_columns = [
{"title": "Contract Code", "data": "contract_code","orderable$
{"title": "Total Revenue (USD)", "orderable":true, "data": "t$
{"title": "Month","data": "month", "orderable":false }
];
extra_data = {'custom_filter':r_filters, "view_type":"monthly" }
}
console.log(r_columns)
$("#tbl_cfms_contract_repos").DataTable({
"ajax": {
"url":'cfms/contract_performance',
"type":'POST',
"data":{'extra_data':extra_data },
"beforeSend": function(request) {
request.setRequestHeader("X-CSRFToken", getCookie("csrftoken") $
},
"dataSrc":'data',
},
"dom":"Bfrtip",
"bProcessing":true,
"bServerSide":true,
"bDestroy":true,
"columns":r_columns,
});
}
This question has an accepted answers - jump to answer
Answers
Hi @hey_danish ,
At a glance it all looks like it should work. We're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.
Cheers,
Colin
One thought after pressing Send, is that if you destroy the table with the initialisation option
destroy
it destroys the DataTables handle, but leaves the table in the DOM as it was - so if you're flicking to the lifetime view, the monthly three columns would still be there. On re-initialisation, it would still have those three columns.You may need to use the
destroy()
method, as this will remove the table entirely from the DOM. You could then reinsert it with the correct width.Hope that helps,
Cheers,
Colin
@colin : Thank you for the response,
I have tried with that way too, It still not working.
I have replicated the same issue here, Please check
live.datatables.net/paxegego
Hi @hey_danish ,
The problem was my second message above - the table wasn't being reset, so it was keeping the three columns. In this forked fiddle here it's entirely removing it and readding it - seems to be doing what you want.
Cheers,
Colin
You are too cool! Thanks a lot