Update Columns in Tabulator

Viewed 1490

Is there a way to only update the columns in the Tabulator table on an event?

var table = new Tabulator("#example-table", {
                data: tableData,
                // autoColumns: true,
                layout: "fitColumns",
                movableColumns: true,
                columns: [{
                        title: "countyname",
                        field: "countyname"
                    }, //link column to name property of user object
                    {
                        title: "2016",
                        field: "2016"
                    }
                ],
            });

Specifically, I'm trying to change the field and title from "2016" to "2017" on a change event. I've found this in the docs:

table.updateData([{id:1, name:"bob", gender:"male"}, {id:2, name:"Jenny", gender:"female"}]);

But as I understand it, that's to update the entire data set, which I'm not intending on doing. I have tried creating a string object in the change event and feeding it into the object manually, but Tabulator doesn't like the fact that it's a string apparently and gives this error:

tabulator.min.js:3 Data Loading Error - Unable to process data due to invalid data type 
Expecting: array 
Received:  string 
Data:      2017

Here's a sample of tableData:

enter image description here

1 Answers

//define some sample data
const tableData1 = [{
    countyname: "Canada",
    2016: "2016",
  },
  {
    countyname: "India",
    2016: "2016",
  },

];
const tableData2 = [{
    countyname: "Canada",
    2017: "2017",
  },
  {
    countyname: "India",
    2017: "2017",
  },

];

const columns1 = [{
    title: "countyname",
    field: "countyname"
  }, //link column to name property of user object
  {
    title: "2016",
    field: "2016"
  }
];

const columns2 = [{
    title: "countyname",
    field: "countyname"
  }, //link column to name property of user object
  {
    title: "2017",
    field: "2017"
  }
];

//create Tabulator on DOM element with id "example-table"
const table = new Tabulator("#example-table", {
  data: tableData1,
  layout: "fitColumns",
  movableColumns: true,
  columns: columns1
});

function changeYear() {
  table.setColumns(columns2);
  table.setData(tableData2);
}
<!DOCTYPE html>
<html>

<head>
  <link href="https://unpkg.com/tabulator-tables@4.2.7/dist/css/tabulator.min.css" rel="stylesheet">
  <script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.2.7/dist/js/tabulator.min.js"></script>

</head>

<body>

  <div id="example-table"></div>
  <button onclick="changeYear()">Change Year</button>

</body>

</html>

Related