Aggregates, for table, update with filtering

Aggregates, for table, update with filtering

CharleyCharley Posts: 66Questions: 17Answers: 0

I've got a table and I'd like to be able to add a sum of hours in the footer, and have it update as the table filters change.

any thoughts/examples that are relevant?

Answers

  • kthorngrenkthorngren Posts: 21,303Questions: 26Answers: 4,947
    edited November 2018

    The Footer callback example should get you started:
    https://datatables.net/examples/advanced_init/footer_callback.html

    You would use a selector-modifier of {search: "applied}" in your column() parameters to limit the rows. Similar to the // Total over this page code.

    Kevin

  • CharleyCharley Posts: 66Questions: 17Answers: 0
    edited November 2018

    I'm trying to add the ability to do it to an arbitrary column (I reuse the same startup code and have dozens of different datatables in the site)

    in general, I iterate through the columns, and if there's a data-aggregate tag in the header, I handle it for that column. So far just sum defined, but I'll probably do a unique count, and possibly others.

    I couldn't see how to filter the data from the column, so pulled it via var filteredColumn = api.column( index, {search: "applied"});

    Callback method

    function aggregateFooterCallback( row, data, start, end, display ){
        var api = this.api(), data;
        api.columns().eq(0).each( function ( index ) {
            var column = api.column( index );
            var aggregateType = $(column.header()).data("aggregate");
            if(aggregateType != null){
                if(aggregateType == "sum"){
                    var data = column.data();
                    var totalSumValue = column.data().reduce( function (a, b) {return tableDataToIntVal(a) + tableDataToIntVal(b);}, 0 );
                    var filteredColumn = api.column( index, {search: "applied"});
                    var filteredSumValue = filteredColumn.data().reduce( function (a, b) {return tableDataToIntVal(a) + tableDataToIntVal(b);}, 0 );
                    $( column.footer() ).html(filteredSumValue +" ("+totalSumValue + ")" );
                } else if (aggregateType=="count"){
                    $( column.footer() ).html("TODO: " + aggregateType);
                } else {
                    $( column.footer() ).html("unknown: "+ aggregateType);
                } 
            } else {
                $( column.footer() ).html("");
            }
        } );
    }
    
This discussion has been closed.