Autoupdate kendo grid cell after enter another cell - kendo-ui

I'm quite new using kendo grids.
So far I've managed to do a few stuff and got a workaround for all my problems.
I have a grid with 2 columns.
One column is a product code that the user should enter, and the other is product quantity that should be filled automatically after the user enter the product code. This should be done on change event.
The product quantity is obtained by a service.
So far I have the following code:
var dataSource = new kendo.data.DataSource({
batch: false,
autoSync: false,
data: [],
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductCode: { type: "string", validation: { required: true } },
ProductQuantity: { type: "number", validation: { required: false, editable: false } }
}
}
},
edit: function (e) {
if (e.model.isNew() == false) {
$('[name="ProductQuantity"]').attr("readonly", true);
}
},
change: function (e) {
if (e.action == "itemchange") {
debugger;
apModel.getProductQuantities(e.items[0].ProductCode).ifFetched().then(function (data) {
var data = JSON.parse(data.Response);
})
//how to access next cell???
$("#ap-grid").data("kendoGrid").saveRow();
}
}
});
$("#ap-grid").kendoGrid({
dataSource: dataSource,
pageable: false,
height: 550,
toolbar: ["create"],
columns: [
{ field: "ProductCode", title: "Product Code" },
{ field: "ProductQuantity", title: "Quantity" },
{ command: ["edit", "destroy"], title: " ", width: "250px" }],
editable: "inline",
});
I can't find a way how to access the next cell to add the data to it.
Can you give me a hint?
thanks in advance,
André

When you set e.items[0].ProductQuantity in OnChange event handler grid cell should automatically update value if datasource bind correctly.
According to kendo docs:
e.items - The array of data items that were affected (or read).
That means it reference at original row of datasource.

Related

Kendo UI datepicker value disappear after server filtering in kendo grid

I am using Kendo Grid and filterable mode row. One of the columns is using a kendoDatePicker.
I filter on server and my problem is, when I pick a value on the datePicker, filtering works fine, but when it shows the data, the value doesn't stay in filter input, it disappears.
I am using to set the DatePicker:
$(document).ready(function () {
var grid = $("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "/kukatko/search",
dataType: "json",
cache: false
},
parameterMap: function (data, type) {
if (type == "read") {
var paramMap = kendo.data.transports.odata.parameterMap(data.filter);
return paramMap;
}
}
},
serverFiltering: true,
pageSize: 10
},
filterable: {
mode: "row"
},
sortable: true,
pageable: true,
reorderable: true,
columns: [{...(some other columns)...
}, {
field: "datumZalozenia",
title: "Dátum založenia",
width: "150px",
parseFormats: ["d.M.yyyy"],
format: "d.M.yyyy",
template: "#=kendo.toString(new Date(datumZalozenia), 'd')#",
filterable: {
cell: {
showOperators: false,
operator: "contains",
format: "{0:d.M.yyyy}",
template: function (args) {
args.element.kendoDatePicker({
format: "d.M.yyyy"
});
}
}
}
Here is an image of how it looks (before, select value and after):
I selected 15.7.2015 so filtering on server runs without any problems.

Kendo UI Grid Toolbox Commands (Create, Save, Update) To enable Conditionally

I have a simple Kendo UI Grid. The gird is in batch mode and works fine. I am using Web API to bind the actual CRUD methods.
I have to show hide the Toolbar Buttons conditionally. How and Where (which event) can I create this kind of functionality
For example:
If(user.Role.Permission == "Edit"){
//Show Edit Button else hide
}
Here is the Actual Kendo UI Grid Code
var baseUrl = "/api/TicketType";
var datatype = "json";
var contentType = "application/json";
var datasource = new kendo.data.DataSource({
serverPaging: true,
pageSize: 10,
autoSync: false,
batch: true,
transport: {
read: {
url: baseUrl,
dataType: datatype,
contentType: contentType
},
create: {
url: baseUrl,
dataType: datatype,
contentType: contentType,
type: "POST"
},
update: {
url: baseUrl,
dataType: datatype,
contentType: contentType,
type: "PUT"
},
parameterMap: function (data, operation) {
if (operation !== "read" && data.models) {
return kendo.stringify(data.models);
}
else {
return {
take: data.take,
skip: data.skip,
pageSize: data.pageSize,
page: data.page
}
}
}
},
schema: {
data: "data.$values",
total: "recordCount",
model: {
id: "TypeID",
fields: {
TypeID: { editable: false, type: "number" },
TypeCode: { editable: true, nullable: false, validation: { required: true } },
Description: { editable: true, nullable: false, validation: { required: true } }
}
}
}
});
$("#Grid").kendoGrid({
dataSource: datasource,
toolbar: [
{name: "create", text: "Add New Record"},
{ name: "save", text: "Save Changes" },
{ name: "cancel", text: "Cancel Changes" },
],
columns:
[
{ field: "TypeID", width: 50, title: "ID"},
{ field: "TypeCode", width: 150, title: "Code"},
{ field: "TypeDescription", width: 200, title: "Description"}
]
})
datasource.read(); // This will bind to the grid.
});
Please try with the below code snippet.
$(document).ready(function () {
hidetoolbar();
});
function onDataBound(arg) {
hidetoolbar();
}
function onDataBinding(arg) {
hidetoolbar();
}
function hidetoolbar(){
If(user.Role.Permission != "Edit"){
$("#Grid .k-add").parent().hide();
$("#Grid .k-update").parent().hide();
$("#Grid .k-cancel").parent().hide();
//OR
$("#Grid .k-add").parent().remove();
$("#Grid .k-update").parent().remove();
$("#Grid .k-cancel").parent().remove();
}
}
$("#Grid").kendoGrid({
dataSource: datasource,
dataBound: onDataBound, // Added
dataBinding: onDataBinding, //Added
toolbar: [
{name: "create", text: "Add New Record"},
{ name: "save", text: "Save Changes" },
{ name: "cancel", text: "Cancel Changes" },
],
columns:
[
{ field: "TypeID", width: 50, title: "ID"},
{ field: "TypeCode", width: 150, title: "Code"},
{ field: "TypeDescription", width: 200, title: "Description"}
]
});
If you want to show or hide the toolbar button, you will need to implement the logic in the Databound event of the Grid.
Please see the below example:
JSBin Databound example
Note: Your question is a duplicate of Make Command Button invisible in Kendo Grid.

Kendo Grid Will not populate with server side data

I cannot get Kendo Grid to populate from server side data.
I have a grid builder function as as follows:
var build = function (carrier, date) {
var urlBase = 'my base url';
var datasource = new kendo.data.DataSource({
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
schema: {
model: {
id: 'Id',
fields: {
StatementDate: { type: "string", editable: false },
CobDate: { type: "string", editable: false },
//lots more fields
Status: { type: "string", editable: false },
Matched: { type: "boolean", editable: true }
}
}
},
transport: {
read: function (options) {
var address = urlBase + '/' + carrier + '/' + date;
$.ajax({
url: address,
type: "POST",
data: JSON.stringify(options.data),
contentType: "application/json",
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
});
},
//update function omitted
parameterMap: function (data, operation) {
if (operation == "read") {
return JSON.stringify(data)
}
},
change: function (e) {
var data = this.data();
console.log(data.length); // displays "77"
}
}
});
return datasource;
};
return {
build: build
}
Grid Definition
elem.kendoGrid({
columns: [
{ field: "StatementDate", title: "State Date", width: 125 },
{ field: "CobDate", title: "COB Date", width: 100 },
//lots more fields
{ command: ["edit"], title: " ", width: "85px"}],
resizable: true,
sortable: true,
editable: "inline",
columnMenu: true,
filterable: true,
reorderable: true,
pageable: true,
selectable: "multiple",
change: this.onSelectedRecordChanged,
toolbar: kendo.template($('#' + templateName).html()),
scrollable: {
virtual: true
},
height: 800
});
I trigger the update via a button click. When I look at the response I see the data. Looks good but the grid will not show the data. It has previously worked fine when data was completely client side.
If I break point on the AJAX call back. I see the correct results.
The grid is bound with data bind. The datasource is a property on a viewmodel.
<div id="grid" data-bind="source: dataSource"></div>
At the start of the app. I create view model
var viewModel= kendo.observable(new GridViewModel(...
and bind
kendo.bind($('#grid'), viewModel);
If I look at the datasource attached to the grid, I see data for the page as expected
This has previously worked fine when data was client side.
I have tried using read() on datasource, and refresh() method on grid. Neither seems to work.
Example response content from server
{"Data":[{"Id": //lots more fields, 20 records],"Total":90375,"AggregateResults":null,"Errors":null}
Any help very much appreciated.
I found the cause in datasource schema missing
{ data: 'Data', total: 'Total' }

Cancel the update in inline kendo grid delete the row

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.

How to get selected row data of kendo detail grid

I am able to get the selected row in kendo grid ( master grid), But I am unable to get the selected row data in detail grid. Please provide me a code sample.
Thanks,
abhi
It is like for the main grid. Being childgrid the grid corresponding to details, do:
var row = childgrid.select();
var data = childgrid.dataItem(row);
console.log("row", row);
console.log("data", data);
Where I defined master grid as:
$("#grid").kendoGrid({
...
detailInit: detailInit,
...
});
And details grid is created using the following function when a row in master grid is expanded:
function detailInit(e) {
childgrid = $("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Orders"
},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 5,
filter: { field: "EmployeeID", operator: "eq", value: e.data.EmployeeID }
},
scrollable: false,
sortable: false,
selectable: true,
pageable: true,
columns:
[
{ field: "OrderID", width: "70px" },
{ field: "ShipCountry", title: "Ship Country", width: "110px" },
{ field: "ShipAddress", title: "Ship Address" },
{ field: "ShipName", title: "Ship Name", width: "200px" }
]
}).data("kendoGrid");
}
Running example here : http://jsfiddle.net/OnaBai/2M86L/ (When you click on Show button, its displays in the console of your browser the selected row and its data).
Here a somewhat simpler example on how to get to the data of the clicked row: http://jsfiddle.net/Corne/AQqMH/5/
This is the code where the magic happens:
change: function (arg) {
var selectedData = this.dataItem(this.select());
// selectedData now points to the selected dataSource item!
alert("Clicked id: " + selectedData.id);
}

Resources