tabulator

How to cumulatively add up bottomCalc sum from one page to another page


I'm trying to add the value from bottomCalc cumulatively from page to page. bottomCalc only add the value for the current displayed rows.

{ title: $t('table.amount'), field: 'amount', headerHozAlign: 'center', hozAlign: 'center', formatter: "money", bottomCalc: "sum", },

This is the column info that I pass to tabulator in a component page. I'm not sure how to write a function to calculate bottomCalc sum cumulatively, adding up value page by page. I tried searching around the docs, couldn't find any solution.


Solution

  • Instead of using the sum option for bottomCalc, you can use a custom function to calculate the sum as it accumulates on each page. In the example below, I am getting the page size and current page number to calculate how many rows should be calculated. Then sum the value of each row up to that point. This way each page displays the accumulated sum at the bottom:

    const tabledata = [
      { id: 1, fullName: 'Oli Bob', age: '12', color: 'red' },
      { id: 2, fullName: 'Mary May', age: '1', color: 'blue' },
      { id: 3, fullName: 'Christine Lobowski', age: '42', color: 'green' },
      { id: 4, fullName: 'John Smith', age: '30', color: 'red' },
      { id: 5, fullName: 'Tim Burton', age: '51', color: 'blue' },
      { id: 6, fullName: 'Sean Nimble', age: '72', color: 'green' },
      { id: 7, fullName: 'Kurt Roman', age: '16', color: 'red' },
      { id: 8, fullName: 'Evan Crawley', age: '8', color: 'blue' },
      { id: 9, fullName: 'Christine Lobowski', age: '22', color: 'green' },
      { id: 10, fullName: 'Kayla Martinez', age: '27', color: 'green' }
    ]
    
    const accCalc = (values, data, calcParams) => {
      const pageSize = table.getPageSize()
      const pageNum = table.getPage()
      const count = pageSize * pageNum
      
      let sum = 0
      
      values.forEach((value, index) => {
        if (index < count) {
          sum = sum + +value
        }
      })
      
      return sum
    }
    
    const table = new Tabulator('#example-table', {
      data: tabledata,
      columns: [
        { title: 'Name', field: 'fullName' },
        { title: 'Age', field: 'age', bottomCalc: accCalc },
        { title: 'Favourite Color', field: 'color' }
      ],
      pagination:true,
      paginationSize:4
    })
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <link href="https://unpkg.com/tabulator-tables@5.5.2/dist/css/tabulator.min.css" rel="stylesheet" />
      <script src="https://unpkg.com/tabulator-tables@5.5.2/dist/js/tabulator.min.js"></script>
    </head>
    
    <body>
      <div id="example-table"></div>
    </body>
    
    </html>