Row vs Physical Row vs Visual Row

Hello again. A question on these rows. While I understand their use, I still can’t get this right. This problem begins after sorting the table.

In this screenshot, I have sorted the table by some column. In the cell that is highlighted, I entered the value “5”. However, the last row ended up with the value “5.00”. Here’s why:

// Pretend hook but - for each change, get the entire row's data, apply some 
// formatting or data transform, and then set the value again
const handleAfterChange = (changes: CellChange[] | null) => {
    for (const [row, col, _original, updated] of changes) {

      // Logs { 0, 1, 5 }
      const visualRowId = hotTable.toVisualRow(row);
      const physicalRowId = hotTable.toPhysicalRow(row);
      console.log({ physicalRowId, row, visualRowId });

      const rowData = hotTable.getSourceDataAtRow(row);
      const newValue = doSomeMagic(rowData, updated);
      hotTable.setDataAtRowProp(row, col, newValue, "customSource");
    }
  };

This means that

  • row [1] this is the current visual index of the row
  • visualRowId [5] this is the row unintentionally being changed
  • physicalRowId [0] this is where the row is when unsorted

So calling setDataAtRowProp(1) is actually changing visual row 5…

I’m just having a hard time telling what I’m supposed to use in all of these situations. It seems whenever I get one right I get the other wrong. For example, in my afterChange hooks, I’m not only trying to format values of the cell I just modified, but also calculate other cells based on the values. After sorting, I keep affecting the wrong cells.

These are the functions I am interested in using in the loop from afterChange that has a row in the CellChanges[] array…

  • setCellMeta
  • getSourceDataAtRow
  • setDataAtRowProp
  • or setSourceDataAtCell?

If you could advise which row, physical row, or visual row ids to use, or which methods to use… that would be so appreciated.

Hi @anthony.agostino

The different hooks you mentioned in the list operates on different indexes (visual or physical). You can translate them using the toPhysical/VisualRow method depending on your needs but that might not work in some cases when you are using the combination of this hooks and indexes are mismatched.

Can you please describe your requirements and send an example showing your current solution? It will be easier that way to recommend the possible solution.

I would have just liked to know which function requires which row type. I just went with trial and error.

@anthony.agostino

The indexes returned by the individual hooks are described in the documentation: Hooks API reference - JavaScript Data Grid | Handsontable