如何设置默认筛选器值和筛选器条目数据表



我有以下情况:

用户可以通过两种方式访问具有数据表的网站:

  1. 正常,没有设置过滤器,您将看到每个条目。
  2. 用户应仅看到具有预定义筛选器的条目

到目前为止,我已经通过在 initComplete-方法中设置过滤器的值以及列的搜索值来完成设置它们,但是设置过滤器后数据表不会更新,这对我来说很神秘,因为数据表在按 F5 后知道设置的过滤器值......

所以我的问题是:如何获得设置默认过滤器值的预期结果,并告诉 DataTable 在完成初始化后进行更新?

我的数据表初始化如下所示:

$('#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();
      }
    });
  }
});
设置

如下所示(这些设置来自 PHP 响应,存储在隐藏字段($('[name="table_settings"]').val()行(上(:

const settings = [
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    { search: 1 } // this will be set to a select box
];

经过一些其他实验,我们可以让它以 1 毫秒的延迟再次绘制列。这使得数据表应用了筛选器。

所以代码现在看起来像这样:

$('#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);
        }
      });
    }
  }
});

最新更新