Create a new column with sum of few other columns in jqgrid

567 views Asked by At

I want to add a column which will contain summation of some columns.

Basically I want to convert following:

enter image description here

to the following:

enter image description here

But this has to be done dynamically i.e. I shall provide colModel id of th e columns I want the summation of.

P.S. Using 4.13.5 version of free-jqgrid.

1

There are 1 answers

0
Oleg On BEST ANSWER

The most easy way to implement your requirements would be the usage of jsonmap and sorttype defined as function, which returns the calculated value of the column. Additionally you would need to implement afterSetRow callback, which fixes the value after modification the row (after setRowData).

The corresponding implementation could be like in the demo. The demo defines the grid with total column, which displays the sum of amount and tax columns. The code of the demo looks as following:

var calculateTotal = function (item) {
        return parseFloat(item.amount) + parseFloat(item.tax);
    };

$("#list").jqGrid({
    ...
    colModel: [
        ...
        { name: "amount", template: "number", ... },
        { name: "tax", template: "number", ... },
        { name: "total", width: 76, template: "number", editable: false,
            jsonmap: function (item) {
                return calculateTotal(item);
            },
            sorttype: function (cellValue, item) {
                return calculateTotal(item);
            }},
        ...
    ],
    afterSetRow: function (options) {
        var item = options.inputData;
        if (item.total === undefined) {
            // test is required to prevent recursion
            $(this).jqGrid("setRowData", options.rowid, {
                total: calculateTotal(item)
            });
        }
    }
    ...
});