Reputation: 121
I Got Columns are quantity,Totalprice in my kendo grid. Then I want to add calculated column to my datagrid. for example:
$("#gridcolumnadd").click(function (e) {
//1.add new column code Column Name is "Price For per kg"
//2.Set Column type is number
//3.Set Column aggregate is sum for footerTemplate
//4.add calculated values ex:(Totalprice/quantity) to "Price For per kg" with using for loop row count.
//redraw datagrid
});
Is possible to make it in kendo datagrid? **
NOTE
I WANT TO CREATE DATAGRID FIRSTLY THEN ADD NEW COLUMN WITH ITS CALCULATION. THATS THE REASON "I WRITE JUST BUTTON CLICK"
**
For example; It is not working
var raw = grid.dataSource.data();
var length = raw.length;//if ı have many data . I can use For Loop
raw[0].new="Test"; //I think one data we have it
grid.columns.push({ field: "new" });
grid.dataSource.data(raw);
Upvotes: 1
Views: 2677
Reputation: 40887
Some tips:
columns.aggregate
.dataBound
event handler or even using DataSource schema.parse
Lets see how this fits together...
This is my original schema:
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { type: "number" },
ProductName: { type : "text" },
UnitPrice: { type: "number" },
UnitsInStock: { type: "number" }
}
},
...
The first thing is add the Total
which equals UnitPrice
times UnitsInStock
where I'm going to use parse
.
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { type: "number" },
ProductName: { type : "text" },
UnitPrice: { type: "number" },
UnitsInStock: { type: "number" },
Total: { type: "total" }
}
},
parse : function (d) {
$.each(d, function(idx, elem) {
elem.Total = elem.UnitPrice * elem.UnitsInStock;
})
return d;
}
},
as you can see I've added an extra field Total
and then in parse
I iterate to compute the total for each record.
Next is define an aggregate that computes the total for all the data received.
aggregate: [
{ field: "Total", aggregate: "sum" }
]
This simple!
Now lets define the columns of my grid:
columns: [
{ field: "ProductName", title : "Name" },
{ field: "UnitPrice", title: "Price" },
{ field: "UnitsInStock", title:"Units" },
{
field: "Total",
title:"Total",
hidden: true,
aggregates: [ "sum" ],
footerTemplate: "#= sum #"
}
]
Here what is important is Total
column where:
* I define as (initially) hidden using hidden: true
.
* I also define an aggregate
that is the sum
.
* And finally I define a template for printing it.
Finally, I don't need to redraw the grid, it is enough invoking columnShow
...
$("#gridcolumnadd").click(function (e) {
$("#grid").data("kendoGrid").columnShow(3);
});
All this together here : http://jsfiddle.net/OnaBai/63mg9/
Upvotes: 3