Search code examples
javascriptxmldomsapui5sheetjs

Custom function on table column reordering --> change underlying table model


I use SheetJS to upload an excel sheet to a ui.table. While uploading I add a technical ID to my column names, which I will need later on in my project. This is how I am adding the technical ID:

getColumnNames: function(worksheet, aData) {
        var firstRow = aData[0];
        var oColumns = [];
        var cells = Object.keys(worksheet);
        for (var i = 0; i < Object.keys(firstRow).length; i++) {            
            var columnName = Object.keys(firstRow)[i];
            var technicalName = "COL" + ('0' + (i+1)).slice(-2);
            oColumns.push({
                columnId: columnName,
                technicalId: technicalName
            });
        }
    return oColumns;
},

When creating the Model, I bind both the columnId and the technicalId to each column.

My users should have the option to reorder the table columns in order to do a mapping to another table. (Context here is not really relevant) So basically there is another table below my uploaded table and a user should be able to reorder the columns of the "uploadTable" to match them with the table below.

Now in order to do a proper mapping, my technical ID has to be adjusted after the reordering is done. Therefore I'd like to add a function that's being executed after the user clicked a "refresh" button.

This function should adjust the technical columnNames. --> E.g. data gets uploaded, column on position 1 has the technical ID "COL01" now it gets dragged to position 2 --> technical ID should change to COL02 and vice versa.

I believe, the only way to do this is by accessing the DomRef of the table, because that's the only place where the actual current table structure is stored, but I'm not exactly sure how I would proceed.

My reordering function only gets the data so far:

onReorder : function() {
    var table = this.getView().byId("uploadData");
    var currentStructre = table.getDomRef();
},

I would appreciate any hints towards this. If anything is unclear, I'm happy to explain it!


Solution

  • sap.ui.table.Table allows its columns to be reordered by dragging and dropping, and the event columnMove is fired after.

    One could keep track of and update some sequence label (e.g. ids) using an approach like this:

    Remember ids (for example column label as id):

    ids = oTable.getColumns().map(oColumn => oColumn.getAggregation('label').getText())
    

    Update ids:

    oTable.attachColumnMove(function(oEvent) {
      var from = oEvent.getParameter('column').getIndex();
      var to = oEvent.getParameter('newPos');
      var name = names.splice(from, 1);
      names.splice(to, 0, name);
      // Then write new ids to model;
    })