My Kendo UI grid is dynamic, where the columns can be defined as field0
, field1
through field[n]
; I do NOT know the number
By looking at the first row of data from the datasource, you can iterate the properties to get all the fields and build dynamically the columns and row template of the grid and the model fields of the dataSource:
var ColsFieldsRowTemplate = {}
function GetRowTemplate(){
var obj = {};
var columns= [];
var fields = {};
var t = '<tr data-uid="#= uid #">';
//use first row of data to get the fields
var row = myData[0];
for (var key in row) {
if (key == 'field0'){
fields[key] = { type: "string" };
columns.push({"field": key});
t += '<td >#= ' + key + ' #</td>';
} else if (key.indexOf("field") > -1){
fields[key] = { type: "number" };
columns.push({"field": key});
t += '<td style="background-color: #=' + key + ' > 3000000 ? "red" : "green" #;">#= ' + key + ' #</td>';
}
}
t += '</tr>';
ColsFieldsRowTemplate.rowTemplate = t;
ColsFieldsRowTemplate.cols = columns;
ColsFieldsRowTemplate.fields = fields;
console.log(ColsFieldsRowTemplate);
return ColsFieldsRowTemplate;
}
GetRowTemplate();
vm.userGridOptions = {
selectable: true,
sortable: true,
pageable: true,
rowTemplate: ColsFieldsRowTemplate.rowTemplate,
columns: ColsFieldsRowTemplate.cols,
editable: {
mode: "popup"
//template: kendo.template($("#editorTemplate").html()) // loaded up in index.html (alt. kendo.template('<div>..</div>') )
},
toolbar: ["create"]
};
// DEFINE DATA SOURCE FOR USER KRIs
vm.gridDS = new kendo.data.DataSource({ // customized User KRI grid; pull from server or localStorage
pageSize: 10,
transport: {
read: function(options){
options.success(myData)
}
},
schema: {
model: {
id: "id",
fields: ColsFieldsRowTemplate.fields
}
}
});
Updated PLUNKER
I think it will be hard to sync the columns with the column headers if you use a row template. What I'd do is use a dynamically created client template and place the business logic inside that one instead.
function getTemplate(field, fieldName){
var color;
if(field[fieldName] > 4000000){
color = "green";
}else{
color = "red";
}
return "<span style='background-color: " + color + "'>" + field[fieldName] + "</span>";
}
vm.userGridOptions = {
selectable: true,
sortable: true,
pageable: true,
columns: [
{ field: "field0" },
{ field: "field1",
template: (function(dataItem){
return getTemplate(dataItem, "field1");
})
},
Example:
http://plnkr.co/edit/lPUzfu?p=preview