linuxatico
linuxatico

Reputation: 1896

How to add\remove column to dataTables "aoColumns" in rendering based on condition

I have a js function working on a table used in 2 sections, these 2 sections differs only for a td, I want to use this same function twice but with a parameter that tells me if to add or not to add this column data to rendering. It is a common task but I cannot achieve it with dataTables.

function find(url, type)
{
    $('#table').dataTable({
        "bProcessing": true,
        "sAjaxSource": url,
        "sAjaxDataProp": "",
        "bDeferRender": true,
        "sPaginationType": "full_numbers",
        "bStateSave": true,
        "bAutoWidth": true,
        "bDestroy":true,
        "aoColumns":
        [
            {"mData": "a"},
            {"mData": "b"},
            {"mData": "conditionalData"}
        ],
        "oLanguage":
        {
            "sLengthMenu": "Mostra _MENU_ risultati per pagina",
            "sZeroRecords": "Nessun RISULTATO",
            "sInfo": "Mostra da _START_ a _END_ di _TOTAL_ risultati",
            "sInfoEmpty": "Mostra 0 su 0 di 0 risultati",
            "sInfoFiltered": "(Filtrati da _MAX_ risultati totali)",
            "sSearch": "Filtra:",
            "oPaginate":
            {
                "sFirst": "|<",
                "sLast": ">|",
                "sNext": ">",
                "sPrevious": "<"
            }
        },
        "aoColumnDefs": [ {"bSortable": false, "aTargets": []} ]
    });
}

Other than initialize all parameters by the constructor, is there a way to do something like the following? I wanna follow this good rule :

"bDestroy":true,
"aoColumns":
[
    {"mData": "a"},
    {"mData": "b"},
    if(type == 1)
    {
        {"mData": "conditionalData"}
    }
],
"oLanguage":

Upvotes: 0

Views: 4451

Answers (1)

AnthonyLeGovic
AnthonyLeGovic

Reputation: 2335

You can do the trick by adding each columns to your datatables. Then, you can hide some column (which ones -not- matching your criteria) using fnSetColumnVis function :

var oTable = $('#myTable').dataTable({...});
for(var i = 0; i < columns.length; i++){
    if(columns[i] not matching criteria)
        oTable.fnSetColumnVis(i, false);
}

Upvotes: 2

Related Questions