update DataTable - with new column configuration

30 views Asked by At

I like to create (if not exists) or update a DataTable. There are two cases with the update:

  1. The columns remain the same and only the rows are to be updated
  2. Columns and rows are to be updated (a different data basis) The distinction between creating and updating already works.

// get column names / keys from data array 'new_data' to 'columnNames'
// ...

if ($.fn.dataTable.isDataTable(table_id))  {
    let datatable = $(table_id).DataTable();
    datatable.clear();
    datatable.rows.add(new_data);
    datatable.draw('full-hold'); // keep current page
} else {
    $(table_id).DataTable({  
        data: new_data,                      
        columns: columns_array
    });
}            

How do I differentiate between updates with and without columns? My idea was to check in the if-clause, weather the current table names equals the columnNames of the new data. I tried datatable.columns().names() which is considered as no function.

The initial setup of the table is defined in HTML:

<table id="my_dataTable" class="table table-bordered display compact">

</table>```` 
1

There are 1 answers

3
fortnut159 On
if ($.fn.dataTable.isDataTable(table_id))  {
    let datatable = $(table_id).DataTable();
    
    // Get the column names of the existing DataTable
    let existingColumnNames = datatable.columns().header().toArray().map(header => $(header).text());

    // Check if the existing column names match the column names of the new data
    let columnNamesMatch = JSON.stringify(existingColumnNames) === JSON.stringify(columnNames);

    if (columnNamesMatch) {
        // Only rows need to be updated
        datatable.clear();
        datatable.rows.add(new_data);
        datatable.draw('full-hold'); // keep current page
    } else {
        // Both columns and rows need to be updated
        datatable.clear();
        datatable.destroy(); // Destroy the existing DataTable
        $(table_id).DataTable({  
            data: new_data,                      
            columns: columns_array
        });
    }
} else {
    $(table_id).DataTable({  
        data: new_data,                      
        columns: columns_array
    });
}