The easiest way of getting it is defining an extra column (lets call it Sum
) in the Grid
that computes the value for you. This extra column uses a template for compute the value and this computation can be either invoking a function in your model (the cleanest) or directly hard code it.
Example:
// DataSource Definition
var ds = new kendo.data.DataSource({
data: [
{ Id:1, User: "John", Jan : 1000, Feb: 2000, Mar: 3000 },
{ Id:2, User: "Peter", Jan : 1500, Feb: 2500, Mar: 3500 }
],
pageSize: 10,
schema: {
model: {
id: "Id",
fields: {
Id: { type: 'number' },
User: { type: 'string' },
Jan: { type: 'number' },
Feb: { type: 'number' },
Mar: { type: 'number' }
},
Sum: function() {
return this.Jan + this.Feb + this.Mar;
}
}
}
});
Where I've defined a Sum
function that computes the total for the fields Jan
through Mar
.
Then the Grid definition would be:
var grid = $("#grid").kendoGrid({
dataSource: ds,
pageable: true,
columns: [
{ field: "User" },
{ field: "Jan" },
{ field: "Feb" },
{ field: "Mar" },
{ title: "Sum", template: "#= Sum() #" }
]
}).data("kendoGrid");
NOTE: I'm not including the aggregates since you do not have problems with this.
As you can see the Sum
column computes the sum when invoked from the template. See it here : http://jsfiddle.net/OnaBai/Bz3Y5/
The second approach would be not having Sum
function but computing the value in the template.
var grid = $("#grid").kendoGrid({
dataSource: ds,
pageable: true,
columns: [
{ field: "User" },
{ field: "Jan" },
{ field: "Feb" },
{ field: "Mar" },
{ title: "Sum", template: "#= data.Jan + data.Feb + data.Mar #" }
]
}).data("kendoGrid");
See it implemented here: http://jsfiddle.net/OnaBai/Bz3Y5/2/
The disadvantage with this two approaches is that you have to compute the total each time the template is invoked so if you paginate you might have some extra processing. If you want to avoid this, then you can use parse
function in the DataSource
:
var ds = new kendo.data.DataSource({
data: [
{ Id:1, User: "John", Jan : 1000, Feb: 2000, Mar: 3000 },
{ Id:2, User: "Peter", Jan : 1500, Feb: 2500, Mar: 3500 }
],
pageSize: 10,
schema: {
model: {
id: "Id",
fields: {
Id: { type: 'number' },
User: { type: 'string' },
Jan: { type: 'number' },
Feb: { type: 'number' },
Mar: { type: 'number' }
}
},
parse: function (d) {
$.each(d, function (idx, elem) {
elem.Sum = elem.Jan + elem.Feb + elem.Mar;
});
return d;
}
}
});
This parse
function receives the original data and transforms it in whatever you want, adding, removing, transforming any field in the original data and before sending it to the Grid.
You can see this last approach here : http://jsfiddle.net/OnaBai/Bz3Y5/3/