Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically create a new row and put that row in edit mode in Kendo grid

In my Kendo grid I am trying to put the 'create new item' button in the header (title) of the command column instead of the toolbar. Here is part of my grid definition:

var grid = $("#grid").kendoGrid({
columns: [{ command: { name: "edit", title: "Edit", text: { edit: "", cancel: "", update: "" } },
headerTemplate: "<a onclick ='NewItemClick()' class='k-button k-button-icontext k-create-alert' id='new-item-button' title='Click to add a new item'><div>New Item</div></a>"},

My question is: how to create a new row and put that row in edit mode in 'NewItemClick()'

like image 886
user3189690 Avatar asked Jan 13 '14 09:01

user3189690


2 Answers

There are some troublesome scope issues when you try to bind the click event in the template definition itself.

Instead, it is easier to assign the link an ID, and then bind the click event later. Notice that I've given it id=create.

headerTemplate: "<a id='create' class='k-button k-button-icontext k-create-alert' id='new-item-button' title='Click to add a new item'><div>New Item</div></a>"

Then in document ready, I bind the click event:

$("#create").click(function () {
    var grid = $("#grid").data("kendoGrid");
    if (grid) {
        //this logic creates a new item in the datasource/datagrid
        var dataSource = grid.dataSource;
        var total = dataSource.data().length;
        dataSource.insert(total, {});
        dataSource.page(dataSource.totalPages());
        grid.editRow(grid.tbody.children().last());
    }
});

The above function creates a new row at the bottom of the grid by manipulating the datasource. Then it treats the new row as a row "edit". The action to create a new row was borrowed from OnaBai's answer here.

Here is a working jsfiddle, hope it helps.

like image 104
gitsitgo Avatar answered Sep 20 '22 19:09

gitsitgo


I would like to complete on gisitgo's answer. If your datasource takes some time to update, when calling page(...), then the refresh of the grid will cancel the editor's popup. This is averted by binding the call to editRow to the "change" event :

var grid = $("#grid").data("kendoGrid");
if (grid) {
  //this logic creates a new item in the datasource/datagrid
  var dataSource = grid.dataSource;
  var total = dataSource.data().length;
  dataSource.insert(total, {});
  dataSource.one("change", function () {
    grid.editRow(grid.tbody.children().last());
  });
  dataSource.page(dataSource.totalPages());
}

NB: This approach will yield problems if your grid is sorted because the new row will not necessarily be at the end

like image 45
Eregrith Avatar answered Sep 20 '22 19:09

Eregrith