This recipe demonstrates how to work with aggregates; for example, counting the number of items in a column.
Copy the following code into your new document:
<!DOCTYPE html> <html> <head> <title>Kendo UI Grid How-to</title> <link rel="stylesheet" type="text/css" href="kendo/styles/kendo.common.min.css"> <link rel="stylesheet" type="text/css" href="kendo/styles/kendo.default.min.css"> <script src="kendo/js/jquery.min.js"></script> <script src="kendo/js/kendo.web.min.js"></script> <script src="js/personData.js"></script> </head> <body> <h3 style="color:#4f90ea;">Exercise 8 - Working with Aggregates</h3> <p><a href="EB9781849699136_3.html">Home</a></p> <script type="text/javascript"> $(document).ready(function() { var myDataSource = new kendo.data.DataSource({ data: personData, schema: { model: { fields: { FirstName: { type: "string" }, LastName: { type: "string" }, Rank: { type: "string" }, DOB: { type: "string" }, PersonId: { type: "number" } } } }, aggregate: [ { field: "Name", aggregate: "count" } ] } ); $("#myGrid").kendoGrid({ dataSource: myDataSource, columns: [ { field: "Name", title: "Full Name", width: "300px", template: '#=FirstName# #=LastName#', footerTemplate: "Total Count: #=count#" }, { field: "DOB", title: "Date of Birth", width: "300px", format: "{0:yyyy-MM-dd}" }, { field: "Age", title: "Age", width: "300px", template: kendo.template( $("#ageTemplate").html() ), headerTemplate: "Age, Assuming Year is 2500" }, { field: "Rank", title: "Rank", width: "300px" } ] }); }); </script> <script type="text/x-kendo-template" id="ageTemplate"> #age = DOB;# #age = 2500 - age.substring(age.length - 4, age.length);# #=age# </script> <div id="myGrid"></div> </body> </html>
In this example, we added the aggregate
parameter to our datasource and specified that we wanted to make the record count of the Name
column available. If we were working with a numeric datatype, we could also specify that we wanted the sum, min, max, or average. Unfortunately, we are limited to those variables when outputting to footerTemplate
, such as the one we are using on the Name
column.
You'll also notice that I added a column named Age
, which is calculated dynamically from DOB
. It's worth mentioning again that you cannot access dynamic variables in footerTemplate
like you can in template
. So, in this case, if you wanted to output the average age in the footer template of the Age
column, you couldn't do it using Kendo aggregates.