Search code examples
javascripttabulatortabulator-py

Tabulator - Calculated Field TopCalc


I need to calculate the growth of this year over Last Year ( (TY - LY) / LY) ... I can create a calculated field, however I'm not able to create a suitable function to calculate the total growth.

my table: enter image description here

the Total Growth value should be like ( 15 - 12 ) / 12 * 100 = 25

My Code is the following:

<html>
<body>

<div id="example-table"></div>

</body>

<script>

//define data array
var tabledata = [{'LOCNAME': 'Location_A',
'SLREVENUE': 6,
'SLREVENUE_LY': 4},
{'LOCNAME': 'Location_B',
'SLREVENUE': 9,
'SLREVENUE_LY': 8}];

//initialize table
var table = new Tabulator("#example-table", {
    data:tabledata,           //load row data from array
    layout:"fitColumns",      //fit columns to width of table
    columns:[                 //define the table columns
        {title:"Location", field:"LOCNAME"},
        {title:"Revenue", field:"SLREVENUE", topCalc:"sum"},
        {title:"Revenue_LY", field:"SLREVENUE_LY", topCalc:"sum"},
        {title:"Growth", field:"SLGROWTH", mutator:function(value, data){return (data.SLREVENUE - data.SLREVENUE_LY) / data.SLREVENUE_LY * 100;},
    }
    ],
});

</script>
</html>

any help please ?

I need to have a function that calculate Growth in topCalc Paramter


Solution

  • For the header you need to add a custom function for the topCalc property that accesses the table.getCalcResults(). Something like:

    columns:[
        ...
        {title: 'Growth', ..., topCalc: function(_v,_d,_p) { 
                let topres = table.getCalcResults().top;
                //console.log("TopCalc top results", topres);
    
                return (topres["SLREVENUE"] - topres["SLREVENUE_LY"]) / topres["SLREVENUE_LY"] * 100;                
            }
        }
    ]
    

    See Custom Calculation Function and Calculation Results in the docs.

    I updated an older Codepen I had with an extra column to show this. See the definition for the AggregateFn column and the getManipulatedTotal function that implements it.