Dynamic table clear problems

Dynamic table clear problems

warningx06warningx06 Posts: 4Questions: 3Answers: 0

I have a datatable element that I created dynamically. Columns in this datatable change dynamically. For example, there may be 5 columns or 7 columns. I try to clear and recreate the DataTable every time it is created. I'm having a problem here. If I have created 5 columns, I have no problem if there are 5 columns in my next operations, but when there are 6 columns, it gives an error. So the created column remains constant and it always asks me to continue with the same number of columns. How do I solve this? Thanks a lot.

if (table !== null) {
    $("#example1").DataTable().clear().draw();
  }

  function formatDateTime(data, type, full, meta) {
    if (type === "display" && data) {
      return moment(data).format("MMMM D, YYYY HH:mm:ss");
    }
    return data;
  }

  var combinedData = {};

  fetched.forEach(function (item) {
    var key = item.asdasd+ '-' + item.abc;

    if (!combinedData[key]) {
      combinedData[key] = {
        _time: item._time,
        abc: item.abc,
      };
    }

    if (!combinedData[key][item._field]) {
      combinedData[key][item._field] = item._value;
    } else {
      combinedData[key][item._field] += ", " + item.val;
    }
  });

  var combinedDataArray = Object.values(combinedData);

  var columnDefs = [
    { title: "abc", data: "abc", orderable: true },
    {
      title: "asdasd",
      data: "asdasd",
      orderable: true,
      render: formatDateTime,
    },
  ];

  var uniqueFields = [...new Set(fetched.map((item) => item._field))];
  uniqueFields.forEach(function (field) {
    var columnWidth = 100 / uniqueFields.length + "%";
    columnDefs.push({
      title: field,
      data: function (row) {
        return row[field] || "Veri Bulunamadı";
      },
      orderable: true,
      createdCell: function (cell, cellData, rowData, rowIndex, colIndex) {
        if (!cellData || cellData === "Veri Bulunamadı") {
          $(cell).css("color", "white");
          $(cell).css("background-color", "#f78c79"); // Hücre arka plan rengi kırmızı
        }
        else {
          $(cell).css("background-color", "#b3f79e"); // Hücre arka plan rengi yeşil

        }
      },
      width: columnWidth
    });
  });
table = $("#example1")
    .DataTable({
      data: combinedDataArray,
      columns: columnDefs,
      searching: true,
      responsive: true,
      lengthChange: false,
      pageLength: 15,
      bDestroy: true,
      buttons: [
        "copy",
        "csv",
        "excel",
        "pdf",
        "print",
      ],
    })
    .buttons()
    .container()
    .appendTo("#example1_wrapper .col-md-6:eq(0)");

Answers

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974

    You probably need to empty the table like the last example in the destroy() docs.

    Kevin

Sign In or Register to comment.