Search code examples
reactjsag-gridag-grid-react

Adding a custom "ALL" (Total) row to the top of an ag-grid that is selectable like any other row


I have an ag-grid table with 2 columns - one text and one number.

I need to add a custom row to the top of my ag-grid table with the total value of the number column and the word "ALL" in the text column.

This needs to be on the top. And should not change its position even if the table is sorted.

Also, the row should be selectable.

Any help in this regard will be highly appreciated!


Solution

  • Sounds like you are describing Row Pinning which is already a feature in AG Grid. However, since you've also stated that row selection is a requirement, this will not be possible with Row Pinning as it's not supported.

    Instead what I'd recommend is adding an extra row object inside the rowData for the custom row, and handling the update of the number column and the custom row position yourself when necessary:

    If you want to handle the total value of the number column then you can use the following logic:

    function updateTotalRowNode() {
      let totalRowNode;
      let sum = 0;
      gridOptions.api.forEachNode((node) => {
        if (node.data.totalRow) {
          totalRowNode = node;
        } else {
          sum += node.data.gold;
        }
      });
      totalRowNode.setDataValue('gold', sum);
    }
    

    If you want to keep the custom row always on the top row then you can implement the postSort callback:

      postSort: (rowNodes) => {
        // here we put All row on top while preserving the sort order
        let nextInsertPos = 0;
        for (let i = 0; i < rowNodes.length; i++) {
          const athlete = rowNodes[i].data.athlete;
          if (athlete === 'All') {
            rowNodes.splice(nextInsertPos, 0, rowNodes.splice(i, 1)[0]);
            nextInsertPos++;
          }
        }
      },
    
    

    See the following plunker for the implementation.