Cancel the update in inline kendo grid delete the row - kendo-ui

I am using two kendo inline grid parent and child. child grid contains the list of products,when user select the products(multiple selection) from child grid and clicked to save button,it's inserted into an parent grid.
Child grid:
var selectedIds = {};
var ctlGrid = $("#KendoWebDataGrid3");
ctlGrid.kendoGrid({
dataSource: {
data:data1,
schema: {
model: {
id: 'id',
fields: {
select: {
type: "string",
editable: false
},
Qty: {
editable: true,
type: "number",
validation: { min: 1, required: true }
},
Unit: {
editable: false,
type: "string"
},
StyleNumber: {
editable: false,
type: "string"
},
Description: {
editable: false,
type: "string"
}
}
}
},
pageSize: 5
},
editable: 'inline',
selectable: "multiple",
sortable: {
mode: 'single',
allowUnsort: false
},
pageable: true,
columns: [{
field: "select",
title: " ",
template: '<input type=\'checkbox\' />',
sortable: false,
width: 35},
{
title: 'Qty',
field: "Qty",
width:90},
{
field: 'Unit',
title: 'Unit',
width: 80},
{
field: 'StyleNumber',
title: 'Style Number',
},
{
field: 'Description',
width: 230},
{command: [<!---{text:"Select" ,class : "k-button",click: selectProduct},--->"edit" ], title: "Command", width: 100 }
],
dataBound: function() {
var grid = this;
//handle checkbox change
grid.table.find("tr").find("td:first input")
.change(function(e) {
var checkbox = $(this);
var selected = grid.table.find("tr").find("td:first input:checked").closest("tr");
grid.clearSelection();
//persist selection per page
var ids = selectedIds[grid.dataSource.page()] = [];
if (selected.length) {
grid.select(selected);
selected.each(function(idx, item) {
ids.push($(item).data("id"));
});
}
})
.end()
.mousedown(function(e) {
e.stopPropagation();
})
//select persisted rows
var selected = $();
var ids = selectedIds[grid.dataSource.page()] || [];
for (var idx = 0, length = ids.length; idx < length; idx++) {
selected = selected.add(grid.table.find("tr[data-id=" + ids[idx] + "]") );
}
selected
.find("td:first input")
.attr("checked", true)
.trigger("change");
}
});
var grid = ctlGrid.data("kendoGrid");
grid.thead.find("th:first")
.append($('<input class="selectAll" type="checkbox"/>'))
.delegate(".selectAll", "click", function() {
var checkbox = $(this);
grid.table.find("tr")
.find("td:first input")
.attr("checked", checkbox.is(":checked"))
.trigger("change");
});
save button clicked Event
function selectProduct()
{
//Selecting child Grid
var gview = $("#KendoWebDataGrid3").data("kendoGrid");
//Getting selected rows
var rows = gview.select();
//Selecting parent Grid
var parentdatasource=$("#grid11").data("kendoGrid").dataSource;
var parentData=parentdatasource.data();
//Iterate through all selected rows
rows.each(function (index, row)
{
var selectedItem = gview.dataItem(row);
var selItemJson={id: ''+selectedItem.id+'', Qty:''+selectedItem.Qty+'',Unit:''+selectedItem.Unit+'',StyleNumber:''+selectedItem.StyleNumber+'',Description:''+selectedItem.Description+''};
//parentdatasource.insert(selItemJson);
var productsGrid = $('#grid11').data('kendoGrid');
var dataSource = productsGrid.dataSource;
dataSource.add(selItemJson);
dataSource.sync();
});
closeWindow();
}
Parent Grid:
var data1=[];
$("#grid11").kendoGrid({
dataSource: {
data:data1,
schema: {
model: { id: "id" ,
fields: {
Qty: { validation: { required: true } },
Unit: { validation: { required: true } },
StyleNumber: { validation: { required: true } },
Description: { validation: { required: true } }
}
}
},
pageSize: 5
},
pageable: true,
height: 260,
sortable: true,
toolbar: [{name:"create",text:"Add"}],
editable: "inline",
columns: [
{field: "Qty"},
{field: "Unit"},
{field: "StyleNumber"},
{field: "Description"},
{ command: ["edit", "destroy"], title: " ", width: "172px" }]
});
$('#grid11').data().kendoGrid.bind("change", function(e) {
$('#grid11').data().kendoGrid.refresh();
});
$('#grid11').data().kendoGrid.bind('edit',function(e){
if(e.model.isNew()){
e.container.find('.k-grid-update').click(function(){
$('#grid11').data().kendoGrid.refresh();
}),
e.container.find('.k-grid-cancel').click(function(){
$('#grid11').data().kendoGrid.refresh();
})
}
})
Adding data into parent grid work nicely,no issue,but when i select the parent grid add new row to edit then trigger the cancel button row was deleted.
I am not able to figure out the problem.please help me.

I found the error, hope can help you.
If you did not config the dataSource: schema: model's "id" field, when click edit in another row before update or click cancel, it will delete the row.
var dataSource = new kendo.data.DataSource({
...
schema: {
model: {
id:"id", // Look here, if you did not config it, issue will happen
fields: {...
...}
}
}
...
})

I have the same issue, and I config cancel like :
...
cancel: function(e) {
this.refresh();
},
...
I don't think it's the best way, but it's working.
Hope another people can give us a better way.

after saving I call $('#grid').data('kendoGrid').dataSource.read();
that cancels the edit row and reads any changes.

Still doesn't seem to be fixed.
I'm addressing it with 'preventDefault()'. This may require explicit closing of window as a consequence.
cancel: function (e) {
// Not sure why this is needed but otherwise removes row...
e.preventDefault();
e.container.data("kendoWindow").close();
},

schema: {
model: { id: "StyleNumber" // "Any ID Field from the Fields list" ,
fields: {
Qty: { validation: { required: true } },
Unit: { validation: { required: true } },
StyleNumber: { validation: { required: true } },
Description: { validation: { required: true } }
}
}
}
This will solve your problem.

Related

Empty column after DataSource Query in Kendo

After making a call to DataSource.Query(), I am unable to call grid.setOption() function. If I do, it returns just an empty grid.
I have searched through several forums but no luck so far.
Just calling setOption works as intended in the grid.
this.grid.setOptions({scrollable: true, autoBind: true});
But when I make a call to query function and then call setOption, it loads an empty grid.
this.jobKendoGrid.dataSource.query({
sort: sort,
filter: filter,
pageSize: this.jobKendoGrid.dataSource.pageSize(),
page: 1
})
I think after making dataSource.Query call, the remote call is being disconnected. Guess that's why I am unable to call setOption, but how can I connect back to remote data source?
PS: Edit
The reason I want to call setOption again, is that I have a toolbar option in every grid that I can do "FitToScreen". This option will shink all columns into the screen.
public fitToScreen() {
for (var i = 0; i < this.grid.columns.length; i++) {
if (this.grid.columns[i].title && this.grid.columns[i].title != "Edit" && this.grid.columns[i].title != " ") {
// console.log(this.grid.columns[i].width);
delete this.grid.columns[i].width;
}
}
//setOption Call
this.grid.setOptions({ scrollable: true });
// https://www.telerik.com/forums/grid-setoptions-causes-empty-grid
if (this.grid.options.autoBind === false) {
this.grid.refresh();
}
}
Found a similar query on the grid forum. One of the answers suggested using getOptions() followed by setOptions() doing that resolves the issue.
<div id="example">
<div id="grid"></div>
<button onclick="filterGrid()">Filter Grid</button>
<script>
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
height: 550,
filterable: {extra: false, mode: "row"},
sortable: true,
pageable: true,
columns: [{
field:"OrderID",
filterable: false
},
"Freight",
{
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name", width: 200
}, {
field: "ShipCity",
title: "Ship City", width: 200
}
]
});
});
function filterGrid()
{
var grid = $("#grid").data("kendoGrid");
var sort= { field: "Freight", dir: "desc" };
var filter ={ field: "Freight", operator: "gte", value: 100 };
grid.dataSource.query({
sort: sort,
filter: filter,
pageSize: grid.dataSource.pageSize(),
page: 1
});
fitToScreen();
}
function fitToScreen()
{
console.log("fitToScreen");
var grid = $("#grid").data("kendoGrid");
for (var i = 0; i < grid.columns.length; i++) {
if (grid.columns[i].title && grid.columns[i].title != "Edit" && grid.columns[i].title != " ") {
delete grid.columns[i].width;
}
}
var currOpt = grid.getOptions();
//Check values of options you want to set
console.log(currOpt.sortable);
//setOptions call
grid.setOptions(currOpt);
//refresh call
grid.refresh();
}
</script>
</div>

kendoui grid cell editor of dropdownlist

I created a KendoUI grid where the first column uses a custom editor. After editing, it doesn't call request of update, however if it is not using editor it will call request of update. Why?
var columns = [
{ field: 'AccountId', title: '客户名称', locked: false, template: '#= me.detail.brandName(data, \'ID\') #', editor: accountGridEditor, width: 200 },
{ field: 'BankNo', title: '付款银行', template: '#= me.detail.format(data, \'Bank\') #', attributes: { style: 'text-align: left;' }, width: 150 },
{ field: 'UnLinkedAmount', title: '未分配', template: '#= me.detail.format(data, \'UnLinkedAmount\') #', attributes: { style: 'text-align: left;' }, width: 100 },
{ command: ["edit", "destroy"], title: " ", width: "250px" }
];
var dataSource = c.dataSourceOption({
transport: {
read: { url: url.api('Finance/FundJournal') },
update: { url: url.api('Finance/FundJournal', { action: 'post' }) },
destroy: { url: url.api('Finance/FundJournal', { action: 'delete' }), type: 'delete' },
parameterMap: function (data, type) {
console.log(type);
console.log(data);
if (type === 'read') return getReadParameters();
if (type === "update") return data;
if (type === 'create') return data;
if (type === 'destroy') return { id: data.Id };
return data;
}
},
schema: {
model: {
id: "Id",
fields: {
AccountId: { editable: true, nullable: false, validation: { required: true } },
BankNo: { editable: false},
UnLinkedAmount: { editable: false }
}
}
},
filter: [{ field: 'SubType', operator: 'neq', value: 'Id' }]
});
var grid = $("#result").kendoGrid({
dataSource: dataSource,
height: 550,
columns: columns,
editable: "inline",
save:function(e){$.ajax();}
}).data('kendoGrid');
If record property is set from dropdownlist something like this:
change: function() {
options.model.Name = this.value();
options.model.dirty = true;
}
it is necessary explicitly to set that model as dirty, to say to datasource that this record was modified and need to be updated. Otherwise, you can use set().
change: function() {
options.model.set('Name',this.value());
}
That way record is automatically marked as dirty in datasource.

Filter of Kendo UI Grid is not executed for specified column

Here is my MVC view code :-
<div id="reportsDb">
<div id="grid"></div>
<script type="text/x-kendo-template" id="template">
<div class="toolbar" id="template" >
<label class="Status-label" for="Status">Show reports by status:</label>
<input type="search" id="Status" style="width: 150px"/>
</div>
</script>
<script>
$(document).ready(function () {
var path = ""
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "#Url.Action("Report_Read", "Report")",
dataType: "json",
type: "Get",
contentType: "application/json"
}
},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 10,
schema: {
model: {
id: "RequestId",
fields: {
IPAddress: { type: "string" },
RequestQuetime: { type: "date" },
RequestPicktime: { type: "date" },
RequestRespondTime: { type: "date" },
StatusType: { type: "string" },
RequestTimeDifference: { type: "datetime", format: "{0:hh:mm:ss}" },
RequestPickDifference: { type: "datetime", format: "{0:hh:mm:ss}" }
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
sortable: true,
pageable: true,
filterable: {
extra: false,
operators: {
string: {
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to"
}
}
},
toolbar: kendo.template($("#template").html()),
height: 430,
columns: [
{ field: "IPAddress", title: "IP address", width: 100, filterable: true },
{ field: "RequestQuetime", title: "Que time", width: 100, filterable: false },
{ field: "RequestPicktime", title: "Pick time", width: 110, filterable: false },
{ field: "RequestRespondTime", title: "Respond time", width: 100, filterable: false },
{ field: "StatusType", title: "status", width: 110, filterable: { ui: statusFilter } },
{ field: "RequestTimeDifference", title: "Time difference", width: 110, filterable: false },
{ field: "RequestPickDifference", title: "Pick difference", width: 110, filterable: false }
]
});
function statusFilter(element) {
element.kendoDropDownList({
dataSource: {
transport: {
read: {
url: "#Url.Action("RequestStatus_Read", "Report")",
dataType: "json",
type: "Get",
contentType: "application/json"
}
}
},
dataTextField: "Text",
dataValueField: "Value",
optionLabel: "--Select Value--"
});
}
});
</script>
</div>
And below is the Action Method of controller :-
public ActionResult Report_Read()
{
return Json(_oRepository.GetReports().ToList(), JsonRequestBehavior.AllowGet);
}
I want to apply filtering on StatusType filed and for that I have bound this filed with dropdownlist.
And my problem is when I am trying to do filtering by selecting one of the status from download its doing nothing.
I am working according to this example:
http://demos.telerik.com/kendo-ui/grid/filter-menu-customization
From your code, everything seems fine except the Controller Read Action. Now if the controller is being called when you apply filter from the view on Grid then the only change required on your side is below:
public JsonResult Report_Read([DataSourceRequest] DataSourceRequest request)
{
return Json(_oRepository.GetReports().ToList().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
EDIT:
If you don't use Kendo.MVC then you have two option to filtering:
Option 1: Client side filtering
-> You will need to get all the data at read time so when the filtering is applied you have all the data, which is best option if the data source is not large as it saves unwanted controller requests for filtering.
-> First think you need do is subscirbe to filterMenuInit() of grid and add the below Script for client side filtering.
Code:
filterMenuInit: function(e) {
if (e.field == "name") {
alert("apply Filter");
var filter = []
... // Generate filters
grid.dataSource.filter(filters);
}
}
For detailed example: Extact from Kendo Examples
Option 2: Server side filtering
-> I don't have much idea about it, but whilst I was searching for my options to filtering I had came across the below Question which was good but a bit complex for my application. But I think you can use it.
JS Fiddle Sample
Please refer below Link for detailed explanation.
Reference: JS Kendo UI Grid Options
Check your rendered html for string you have in td and string you are filtering
Look if your td has any other code than the string you are trying to filter. If the case is there is some other html code inside td like a span or a div, then you have to refactor your code to make sure you have content only in td.
Make sure you trim your string inside td.
Try contains instead of equal to. if this works them the issue should be extran text/html or triming.
function applyFilter() {
var filters = [], item_filters = [], brand_filters = [], invoice_id = null;
var item_nested_filter = { logic: 'or', filters: item_filters };
var brand_nested_filter = { logic: 'or', filters: brand_filters };
var gridData = $("#invoicelistgrid").data("kendoGrid");
var invoiceId = $("#invoiceidsearch").data("kendoDropDownList").value();
var itemId = $("#itemsearch").data("kendoDropDownList").value();
var brandId = $("#brandsearch").data("kendoDropDownList").value();
var partyId = $("#party-dropdown").data("kendoDropDownList").value();
if (partyId !== "") {
filters.push({ field: "party_id", operator: "eq", value: parseInt(partyId) });
}
if (invoiceId !== "") {
filters.push({ field: "invoice_id", operator: "eq", value: parseInt(invoiceId) });
}
if (itemId !== "") {
for (var i = 0; i < gridData.dataSource._data.length; i++) {
var data = gridData.dataSource._data[i].tb_invoice_lines;
for (var j = 0; j < data.length; j++) {
if (parseInt(itemId) === parseInt(data[j].item_id)) {
item_filters.push({ field: "invoice_id", operator: "eq", value: parseInt(data[j].invoice_id) });
} else {
invoice_id = data[j].invoice_id;
}
}
}
if (item_filters.length > 0) {
filters.push(item_nested_filter);
} else {
filters.push({ field: "invoice_id", operator: "eq", value: parseInt(invoice_id) });
}
}
if (brandId !== "") {
for (var k = 0; k < gridData.dataSource._data.length; k++) {
var brand_data = gridData.dataSource._data[k].tb_invoice_lines;
for (var l = 0; l < brand_data.length; l++) {
console.log("Grid item id = " + brand_data[l].brand_id);
if (parseInt(brandId) === parseInt(brand_data[l].brand_id)) {
brand_filters.push({
field: "invoice_id",
operator: "eq",
value: parseInt(brand_data[l].invoice_id)
});
} else {
invoice_id = brand_data[l].invoice_id;
}
}
}
if (brand_filters.length > 0) {
filters.push(brand_nested_filter);
} else {
filters.push({ field: "invoice_id", operator: "eq", value: parseInt(invoice_id) });
}
}
console.log(filters);
gridData.dataSource.filter({
logic: "and",
filters: filters
});
}

Set the selected text or value for a KendoDropDownList

I'm using Durandal and Kendo UI. My current problem is the edit popup event on my grid. I cannot seem to set the selected value on my dropdown.
I can debug and inspect, and I indeed do see the correct value of e.model.InstrumentName nicely populated.
How can I set the value/text of those dropdowns in edit mode ?
Here's my grid init:
positGrid = $("#positGrid").kendoGrid({
dataSource: datasource,
columnMenu: false,
{
field: "portfolioName", title: "Portfolio Name",
editor: portfolioDropDownEditor, template: "#=portfolioName#"
},
{
field: "InstrumentName",
width: "220px",
editor: instrumentsDropDownEditor, template: "#=InstrumentName#",
},
edit: function (e) {
var instrDropDown = $('#InstrumentName').data("kendoDropDownList");
var portfDropDown = $('#portfolioName').data("kendoDropDownList");
instrDropDown.list.width(350); // let's widen the INSTRUMENT dropdown list
if (!e.model.isNew()) { // set to current valuet
//instrDropDown.text(e.model.InstrumentName); // not working...
instrDropDown.select(1);
//portfDropDown.text();
}
},
filterable: true,
sortable: true,
pageable: true,
editable: "popup",
});
Here's my Editor Template for the dropdown:
function instrumentsDropDownEditor(container, options) {
// INIT INSTRUMENT DROPDOWN !
var dropDown = $('<input id="InstrumentName" name="InstrumentName">');
dropDown.appendTo(container);
dropDown.kendoDropDownList({
dataTextField: "name",
dataValueField: "id",
dataSource: {
type: "json",
transport: {
read: "/api/breeze/GetInstruments"
},
},
pageSize: 6,
select: onSelect,
change: function () { },
optionLabel: "Choose an instrument"
}).appendTo(container);
}
thanks a lot
Bob
Your editor configuration is bit unlucky for grid, anyway i have updated my ans on provided code avoiding manual selections:
Assumptions: Instrument dropdown editor only (leaving other fields as strings), Dummy data for grid
<div id="positGrid"></div>
<script>
$(document).ready(function () {
$("#positGrid").kendoGrid({
dataSource: {
data: [
{ PositionId: 1, Portfolio: "Jane Doe", Instrument: { IID: 3, IName: "Auth2" }, NumOfContracts: 30, BuySell: "sfsf" },
{ PositionId: 2, Portfolio: "John Doe", Instrument: { IID: 2, IName: "Auth1" }, NumOfContracts: 33, BuySell: "sfsf" }
],
schema: {
model: {
id: "PositionId",
fields: {
"PositionId": { type: "number" },
Portfolio: { validation: { required: true } },
Instrument: { validation: { required: true } },
NumOfContracts: { type: "number", validation: { required: true, min: 1 } },
BuySell: { validation: { required: true } }
}
}
}
},
toolbar: [
{ name: "create", text: "Add Position" }
],
columns: [
{ field: "PositionId" },
{ field: "Portfolio" },
{ field: "Instrument", width: "220px",
editor: instrumentsDropDownEditor, template: "#=Instrument.IName#" },
{ field: "NumOfContracts" },
{ field: "BuySell" },
{ command: [ "edit", "destroy" ]
},
],
edit: function (e) {
var instrDropDown = $('#InstrumentName').data("kendoDropDownList");
instrDropDown.list.width(400); // let's widen the INSTRUMENT dropdown list
},
//sortable: true,
editable: "popup",
});
});
function instrumentsDropDownEditor(container, options) {
$('<input id="InstrumentName" required data-text-field="IName" data-value-field="IID" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataSource: {
type: "json",
transport: {
read: "../Home/GetMl"
}
},
optionLabel:"Choose an instrument"
});
}
</script>
Action fetching json for dropddown in Home controller:
public JsonResult GetMl()
{
return Json(new[] { new { IName = "Auth", IID = 1 }, new { IName = "Auth1", IID = 2 }, new { IName = "Auth2", IID = 3 } },
JsonRequestBehavior.AllowGet);
}

Kendo UI toolbar buttons

I am using a Kendo UI grid, which looks like this:
function refreshGrid()
{
$(".k-pager-refresh.k-link").click();
}
var editWindow;
var fields= {FullName: {type: "string"}, Email: {type: "string"}, LogCreateDate: {type: "date"}};
var gridColumns =
[{
width: 90,
command: {
name: "edit",
text: "Edit",
click: function(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
editWindow = $("#edit").kendoWindow({
title: "Edit User",
modal: true,
visible: false,
resizable: false,
width: 800,
height: 400,
content: 'myediturl' + dataItem.ID
});
editWindow.data("kendoWindow").center().open();
return false;
}
}
},
{
width: 90,
command: {
name: "delete",
text: "Delete",
click: function(e) {
//alert(this.dataItem($(e.currentTarget).closest("tr")).ID);
var id = this.dataItem($(e.currentTarget).closest("tr")).ID;
if (confirm("Are you sure you want to delete this user?"))
{
$.ajax({
type: 'POST',
url: '#Url.Action("deleteuser","admin",null, "http")' + "/" + this.dataItem($(e.currentTarget).closest("tr")).ID,
success: function (param) { refreshGrid(); },
async: false
});
}
return false;
}
}
},
{
field: "FullName",
title: "Full Name",
type: "string"
},
{
field: "Email",
title: "Email",
type: "string"
},
{
field: "LogCreateDate",
title: "Created",
type: "date",
template: '#= kendo.toString(LogCreateDate,"MM/dd/yyyy") #'
}];
//getSorts the columns of the grid
function getColumns() {
//Parsing the set of columns into a more digestable form
var columns = "";
for (var col in gridColumns) {
if (!!gridColumns[col].field)
{
if (columns.length > 0) {
columns += ";";
}
columns += gridColumns[col].field + "," + gridColumns[col].type;
}
}
return columns;
}
function getSorts(sortObject) {
if (!(sortObject)) {
return "";
}
//Getting the row sort object
var arr = sortObject;
if ((arr) && (arr.length == 0)) {
return "";
}
//Parsing the sort object into a more digestable form
var columnSet = getColumns();
var returnValue = "";
for (var index in arr) {
var type = "";
for (var col in gridColumns) {
if (gridColumns[col].field === arr[index].field) {
type = gridColumns[col].type;
}
}
returnValue += ((returnValue.length > 0) ? (";") : ("")) + arr[index].field + "," + (arr[index].dir === "asc") + "," + type;
}
return returnValue;
}
var grid;
$(function () {
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "mydatasourceurl",
type: "POST",
},
parameterMap: function (data, type) {
data.filters = JSON.stringify(data.filter);
data.columns = JSON.stringify(getColumns());
data.sorts = JSON.stringify(getSorts(data.sort));
console.log(data);
return data;
}
},
schema: {
fields: fields,
data: "Data",
total: "Total"
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
toolbar: [{
name: "Add",
text: "Add new record",
click: function(e){console.log("foo"); return false;}
}],
height: 392,
groupable: false,
sortable: true,
filterable: true,
pageable: {
refresh: true,
pageSizes: true
},
columns: gridColumns
});
grid = $("#grid").data("kendoGrid");
});
My create toolbar action is not triggered on click. How can I resolve this problem, is Kendo UI able to handle toolbar click events? The best solution I came up with looks like this:
$(".k-button.k-button-icontext.k-grid-add").click(function () {
//If the window doesn't exist yet, we create and initialize it
if (!grids[gridContainerID].addWindow.data("kendoWindow")) {
grids[gridContainerID].addWindow.kendoWindow({
title: "Add " + entityName,
width: "60%",
height: "60%",
close: onClose,
open: onAddOpen,
content: addUrl
});
}
//Otherwise we just open it
else {
grids[gridContainerID].addWindow.data("kendoWindow").open();
}
//Centralizing and refreshing to prepare the layout
grids[gridContainerID].addWindow.data("kendoWindow").center();
grids[gridContainerID].addWindow.data("kendoWindow").refresh();
return false;
});
Thanks in advance.
Instead of using that complex selector use the one that Kendo UI creates from name:
toolbar: [
{
name: "Add",
text: "Add new record",
click: function(e){console.log("foo"); return false;}
}
],
and then:
$(".k-grid-Add", "#grid").bind("click", function (ev) {
// your code
alert("Hello");
});
In kendogrid docs here shows that there is no click configuration for grid toolbar buttons like grid.colums.commands.
To solve this problem you can reference following steps:
create a template for toolbar
<script id="grid_toolbar" type="text/x-kendo-template">
<button class="k-button" id="grid_toolbar_queryBtn">Query</button>
</script>
apply tempate to toolbar
toolbar:[{text:"",template: kendo.template($("#grid_toolbar").html())}]
add event listener to button
$("#grid_toolbar_queryBtn").click(function(e) {
console.log("[DEBUG MESSAGE] ", "query button clicked!");
});

Resources