Search code examples
javascriptkendo-griddynamic-columnskendo-template

Kendo Grid - Dynamic Column and Custom Template


I have a problem with kendo Grid and Custom template. The problem is, I need to check the value of the column

  • if Value == 1, I need to change it to Icon Check
  • If Value == 0, I need to change it to Icon Delete
  • If Value == -1. I need to return empty html

This is the Example Code : Fiddle

var myFields = {
        no: { },
        section: { },
        service: { }
    };
for(var x = 0 ; x < dataList.length; x++){
    myFields["data"+x] = { };
}

    var no = 0;
var myColumns = [
                 { title: "No", locked: true, width: 50, template: function(e){return ++no; } },
                 { field: "section", title: "Hole Section", locked: true, width: 130 },
                 { field: "service", title: "Services", locked: true, width: 200 }
                 /* other columns ... */
             ];
for(var x = 0 ; x < dataList.length; x++){
    myColumns.push( { field: "data"+x, title: dataList[x], width: 100, locked: false});
}

Solution

  • Here is a Working Demo

    Solution: You can change your data fed into the grid by replacing the numbers with a icon. I prefer using FontAwesome Icons as it is very light weight.

    CDN for font awesome.

    https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css

    Code change to make changes into your data is as below.

    tableData[tableData.length - 1]["data"+c] = formatCellData(dataOffset[c].selected); 
    // replace you code with function call.
    

    the function definition is as below.

    function formatCellData(value){
      switch(value){
      case 1:  return "<i class='fa fa-check''></i>";break;
      case 0:  return "<i class='fa fa-trash''></i>";break;
      case -1: return "";break;
      default: return "";
      }
    }
    

    Now this will make sure you get the HTML part instead of the numbers,

    Now we need to make sure the HTML string is read as a regular HTML and icons are displayed and not the HTML string as is, So add this encoded: false attribute into your column data.

    for(var x = 0 ; x < dataList.length; x++){
     myColumns.push( { field: "data"+x, title: dataList[x], width: 100, locked: false,encoded: false});
    }
    

    Hope this helps.