1

I have the following scenario:

A user can visit a site with a DataTable in two ways:

  1. Normal, no filter set, you'll see every entry.
  2. User should see only entries with predefined filters

I've accomplished so far to set the filter's value as well as the column's search value by setting them in the initComplete-method, but the DataTable doesn't updates after setting the filters, which is mysterious to me since the DataTable knows after pressing F5 the set filter value...

So my question is: How do I get the desired result of setting default filter values, and tell the DataTable to update, after it finished it's initialization?

My DataTable-Initialization looks like this:

$('#table-data').DataTable({
  processing: true,
  serverSide: true,
  language: dataTablesGerman,
  initComplete: function () {
    this.api().columns().every(initColumnFilter);
    const json = JSON.parse($('[name="table_settings"]').val());
    const dt = this.api();
    dt.columns().every(function (idx) {
      const column = this;
      if (json[idx] !== null) {
        const $current = $('input:not(.datetimerange), select', this.footer());
        const value = json[idx].search;
        $current.val(value);
        column.search(value).draw();
      }
    });
  }
});

The settings are looking like this (these settings are from the PHP Response, which are stored on a hidden field, the $('[name="table_settings"]').val() line):

const settings = [
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    { search: 1 } // this will be set to a select box
];
  • You may need to reinitialize datatable with updated settings. May be destroy it and initialize again like [this](https://stackoverflow.com/a/30104464/5447994) – Thamilhan Apr 17 '18 at 13:13
  • Didn't work, but found another solution. Seems like it was a timing problem, so I added this line and did the following: `window.setTimeout(function () { column.draw(); }, 1); ` – Pascal Klose Apr 17 '18 at 16:46

1 Answers1

0

After some other experiments we could get it work with drawing the column again with a delay of 1ms. This made the DataTable apply the filter.

So the code now looks like this:

$('#table-data').DataTable({
  processing: true,
  serverSide: true,
  language: dataTablesGerman,
  initComplete: function () {
    this.api().columns().every(initColumnFilter);
    const json = JSON.parse($('[name="table_settings"]').val());
    const dt = this.api();
    if (json !== null && json.length > 0) {
      dt.columns().every(function (idx) {
        const column = this;
        if (json[idx] !== null) {
          const $current = $('input:not(.datetimerange), select', this.footer());
          const value = json[idx].search;
          $current.val(value);
          column.search(value).draw();
          window.setTimeout(function () {
            column.draw();
          }, 1);
        }
      });
    }
  }
});