Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic columns for Handsontable?

I'm working with Handsontable to create a web grid that can copy / paste between web and excel, I tried with code below and it works fine:

  var first = true;
  var exampleGrid = $("#exampleGrid");
  exampleGrid.handsontable({
      rowHeaders: true,
      colHeaders: true,
      stretchH: 'all',
      minSpareCols: 0,
      minSpareRows: 0,
      height: 600,
      columns: [
      { data: "Id", title: "ID", type: "text" }, //'text' is default, you don't actually have to declare it
      { data: "Name", title: "Name", type: "text" },
      { data: "DisplayColor",
      title: "Display Color",
      type: 'autocomplete',
      source: ["yellow", "red", "orange", "green", "blue", "gray", "black", "white"]
      },
      { data: "Description", title: "Description", type: 'text' },
      { data: "IsDeleted", title: "Is Deleted", type: 'checkbox' }
      ],
      colWidths: [400, 100, 60, 100, 50, 40, 40, 60], //can also be a number or a function
      contextMenu: false,
  });

Now I need create web grid with dynamic columns, I tried replace the column list with function below, but it does not works:

    columns:
        function () {
            var cols = [];
            for (var i = 0; i < 1; i++) {
                var col = new Object();

                col.data = "Name";
                col.title = "Name" + i.toString();
                col.type = "text";
                cols[i] = col;
            }
            return cols;
        },

Is it possible to create dynamic columns in Handsontable grid? and how to do it?

I'm a JavaScript beginner, so please tell me if there is any error I made, thanks!

like image 291
xinfli Avatar asked Dec 07 '22 08:12

xinfli


1 Answers

Resolved this problem by myself, function can not be used in column definition directly, but variable is allowed, so code below works:

var dynamicColumns = [];
for (var i = 0; i < 366; i++) {
    var col = new Object();
    col.data = "Name";
    col.title = "Name " + i.toString();
    col.type = "text";
    dynamicColumns.push(col);
}

skillGrid.handsontable({
    // ...
    columns: dynamicColumns,
    // ...
like image 87
xinfli Avatar answered Dec 27 '22 17:12

xinfli