YUI3 DataTable add two rows - datatable

I am trying to modify the the YUI dataTable to add rows dynamically after the dataTable is created but instead of adding one new row it adds two.
My code:
var index = 0;
YUI({
filter: 'RAW'
}).use([
'node',
'io',
'datasource',
'json-parse',
'json-stringify',
'datatable',
'datatable-sort',
'datatable-mutable',
'datatable-scroll',
'datatable-paginator',
'model-list'
],
function(Y) {
var dataTableColumns = [
{
key: 'id',
label: '#'
},
{
key: 'name',
label: 'Name',
allowHTML: true,
formatter: function (valueObject) {
return valueObject.name;
}
}
];
var dataTable = new Y.DataTable({
width: "100%",
columns: dataTableColumns,
plugins: [{
cfg: {
highlightRange: false
},
fn: Y.Plugin.DataTableHighlight
}]
}
);
dataTable.render('#dataTableDiv');
var dataSource = new Y.DataSource.IO({
source: "/localhost/data/"
});
dataSource.plug({fn: Y.Plugin.DataSourceJSONSchema, cfg: {
schema: {
resultFields: [
{key: "id"},
{key: "name"}
]
}
}});
dataTable.plug(Y.Plugin.DataTableDataSource, {
datasource: dataSource
});
dataTable.datasource.load();
Y.one("#addButton").on('click', function (event) {
index++;
var rowData = {
id: index,
name: "Test row"
};
dataTable.addRow(rowData, {index: 0});
});
}
);
So After DataTable is created I have:
And after dataTable.addRow(rowData, {index: 0}); I have:

Related

How to sort time column in jsgrid?

We are binding a table using jqgrid. We have the first column start as a time column with a 12-hour format. We are facing an issue with sorting this data. The data is sorted correctly but it is not taking am/pm into consideration. Below is our code for binding the jqgrid:
var newFieldsArray =
[
{ name: "ID", title: "ID", type: "number", width: "50px", visible: false },
{
name: "TimeStart", title: "Start", type: "customTime", width: "100px", validate: "required",
sorttype: "date",
formatter : {
date : {
AmPm : ["am","pm","AM","PM"],
}
},
// datefmt: "m/d/Y h:i A",
//sorttype: 'datetime', formatter: 'date', formatoptions: {newformat: 'd/m/y', srcformat: 'Y-m-d H:i:s'},
insertTemplate: function () {
var $result = jsGrid.fields.customTime.prototype.insertTemplate.call(this); // original input
$result.val(varendTime);
return $result;
},
itemTemplate: function (value, item) {
return "<b style='display:none'>" + Date.parse(item.StartDate) + "</b><span>" + (item.TimeStart) + "</span>";
}
},
{
name: "TimeEnd", title: "End", type: "customTime", width: "100px", validate: "required",sorttype: "date", datefmt: "h:i"
},
{ name: "TimeTotal", title: "Time", type: "text", width: "50px", readOnly: true },
{
name: "CoilPO", title: "Coil PO", type: "text", width: "50px", validate: "required",
insertTemplate: function () {
var $result = jsGrid.fields.text.prototype.insertTemplate.call(this); // original input
$result.val(varlot);
return $result;
}
},
{ name: "Joints", title: "Joints", type: "integer", width: "60px" },
{ name: "CommercialGrade", title: "Commercial Grade", type: "integer", width: "80px" },
{ name: "QAHold", title: "QA Hold", type: "integer", width: "60px" },
{ name: "Rejected", title: "Reject", type: "integer", width: "60px" },
{ name: "ActionTaken", title: "Reason of Delay / Action Taken", type: "text", width: "120px" },
{
name: "ClassId", title: "Class",
type: "select", items: classDataArr,//classData.filter(function(n){return classdt.indexOf(n.Id) != -1 }),//classData,
valueField: "Id", textField: "Title",
insertTemplate: function () {
debugger;
var taxCategoryField = this._grid.fields[12];
var $insertControl = jsGrid.fields.select.prototype.insertTemplate.call(this);
var classId = 0;
var taxCategory = $.grep(voiceData, function (team) {
return (team.ClassId) === classId && (team.StationId) == parseInt($('#ddlEquipmentName').val());
});
taxCategoryField.items = taxCategory;
$(".tax-insert").empty().append(taxCategoryField.insertTemplate());
$insertControl.on("change", function () {
debugger;
var classId = parseInt($(this).val());
var taxCategory = $.grep(voiceData, function (team) {
return (team.ClassId) === classId && (team.StationId) == parseInt($('#ddlEquipmentName').val());
});
taxCategoryField.items = taxCategory;
$(".tax-insert").empty().append(taxCategoryField.insertTemplate());
});
return $insertControl;
},
editTemplate: function (value) {
var taxCategoryField = this._grid.fields[12];
var $editControl = jsGrid.fields.select.prototype.editTemplate.call(this, value);
var changeCountry = function () {
var classId = parseInt($editControl.val());
var taxCategory = $.grep(voiceData, function (team) {
return (team.ClassId) === classId && (team.StationId) == parseInt($('#ddlEquipmentName').val());
});
taxCategoryField.items = taxCategory;
$(".tax-edit").empty().append(taxCategoryField.editTemplate());
};
debugger;
$editControl.on("change", changeCountry);
changeCountry();
return $editControl;
}
},
{
name: "VoiceId", title: "Voice", type: "select", items: voiceData,
valueField: "Id", textField: "Title", width: "120px", validate: "required",
insertcss: "tax-insert",
editcss: "tax-edit",
itemTemplate: function (teamId) {
var t = $.grep(voiceData, function (team) { return team.Id === teamId; })[0].Title;
return t;
},
},
{ name: "Remarks", title: "Remarks", type: "text", width: "110px" },
{ name: "control", type: "control" }
];
hoursGrid.jsGrid("option", "fields", newFieldsArray);
Below is two screenshots of data that appear when we sort:
Can someone tell me what we are doing wrong?
You're mixing up jsGrid and jqGrid. The way to achieve it in jsGrid is using the built-in sorter jsGrid.sortStrategies.date, I added an example below.
As commented by #Tomy Tomov (the creator of jqGrid), you're using jsGrid, not jqGrid. This is evident both by your code and by the UI in the screenshot.
Specifically, you took the date sorter of jqGrid and used it in your jsGrid code, but (of course) it's not supported there. You can go ahead and look in jsGrid source for AmPm which you used - and see it's not there.
So how to do it in jsGrid?
Just pass the built-in sorter jsGrid.sortStrategies.date to the sorter property. However, it does require Date objects, so if you only got time strings, you'll have to convert those to dates.
Below is a quick demo (jsfiddle), click the date column title to sort:
Note that getData gets a function parameter that is responsible to get all data as Date objects, and that the value of isUTC depends on whether you actually use it
$(document).ready(function () {
const dataFunc = getDataTimes;
$("#jsGrid").jsGrid({
width: "100%",
data: getData(dataFunc),
sorting: true,
fields: [{
name: "name",
type: "text",
width: 50
}, {
name: "date",
type: "date",
width: 50,
sorter: jsGrid.sortStrategies.date,
cellRenderer: (value, item) => {
const withYear = false;
const isUTC = dataFunc == getDataTimes;
return renderDateTime(value, item, withYear, isUTC);
}
}
]
});
});
function getData(getDates) {
const data = [
{name: "a"}, {name: "b"}, {name: "c"},
{name: "d"}, {name: "e"}, {name: "f"},
];
const dates = getDates();
for (let i = 0; i < dates.length; i++) {
data[i].date = dates[i];
}
return data;
}
function getDataDates() {
const date1 = new Date(2022, 10, 1, 4, 50);
const date2 = new Date(2022, 10, 1, 8, 50);
const date3 = new Date(2022, 10, 1, 15, 50);
const date4 = new Date(2021, 10, 1, 4, 50);
const date5 = new Date(2021, 10, 1, 8, 50);
const date6 = new Date(2021, 10, 1, 15, 50);
return [date1, date2, date3, date4, date5, date6];
}
function getDataTimes() {
const time1 = "3:50 AM";
const time2 = "8:50 AM";
const time3 = "4:50 AM";
const time4 = "3:50 PM";
const time5 = "8:50 PM";
const time6 = "4:50 PM";
const times = [time1, time2, time3, time4, time5, time6];
return times.map(t => convertTime12to24(t));
}
function convertTime12to24(time12h) {
const [time, modifier] = time12h.split(' ');
let [hours, minutes] = time.split(':');
if (modifier === 'PM') {
hours = parseInt(hours, 10) + 12;
}
return new Date(Date.UTC(2022,0,1,hours, minutes));
}
function renderDateTime(value, row, withYear, isUTC) {
return `<td>${getDateTimeAsString(value, withYear, isUTC)}</td>`;
}
function getDateTimeAsString(date, withYear, isUTC) {
var options = {
hour: 'numeric',
minute: 'numeric',
hour12: true
};
if (withYear) {
options.withYear = 'numeric';
}
if (isUTC) {
options.timeZone = 'UTC';
}
return date.toLocaleString('en-US', options);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" rel="stylesheet">
<div id="jsGrid" class="jsgrid"></div>
Let me give it a try, we have 2 options to perform Sorting operation in JsGrid:
1.Custom Field (Topic Name you can refer below link)
Reference Link :http://js-grid.com/docs/#grid-fields
In this, you can define custom property in your config and extend it.
You can use sorter property and call your user defined function werein you can logic to sort date with time stamps directly.
2.Sorting Strategies (Topic Name you can refer below link)
Reference Link :http://js-grid.com/docs/#grid-fields
In this, you can create your custom objects and then apply sorting strategies of date directly on to the object to perform sorting operation as per your logic.

Kendo UI for Angular Exporting selected rows to Excel

I'm using Kendo UI for Angular and I am trying to export my grid to Excel. I have implemented a solution like this: https://www.telerik.com/kendo-angular-ui/components/grid/export/excel-export/
and it does work. It exports all rows in my grid. My problem is that I only want to export selected rows. I haven't been able to successfully filter the allData method to only export selected rows.
It looks to me like the process method called from within the allData method can take a State object that has a filter: component. But for the life of me I can't seem to get it to work. Can anybody point me to a simple example where the selected rows only are exported to Excel?
Thanks,
John B.
I have implemented selected rows and selection key to be entire row so that when I export i can retrieve the selected rows and modified export allData to export selection data if exists.If selection doesnot exists then exports all data.
public mySelectionKey(context: RowArgs): string {
// return context.dataItem.serialNumber + " " + context.index;
return context.dataItem;
}
public allData(): ExcelExportData {
let selInventory: Inventory[] = [];
let result: ExcelExportData;
selInventory = JSON.parse(JSON.stringify(this.mySelection));
if (selInventory.length > 0) {
result = {
data: process(selInventory, {
sort: [{ field: "serialNumber", dir: "asc" }]
}).data
};
} else {
result = {
data: process(this.inventoryData, {
sort: [{ field: "serialNumber", dir: "asc" }]
}).data
};
}
return result;
}
Export selected or all rows
function excelExport() {
var exportAll = $('.selectrow').is(":checked");
var grid = $("#grid");
var rows = [{
cells: [
{ value: "column1" },
{ value: "column2" },
{ value: "column3" },
{ value: "column4" },
{ value: "column5" },
{ value: "column6" },
{ value: "column7" }
]
}];
if (exportAll) {
var dataDource = grid.getKendoGrid();
var trs = $("#grid").find('tr');
for (var i = 0; i < trs.length; i++) {
if ($(trs[i]).find(":checkbox").is(":checked")) {
var dataItem = dataDource.dataItem(trs[i]);
rows.push({
cells: [
{ value: dataItem.column1 },
{ value: dataItem.column2 },
{ value: dataItem.column3 },
{ value: dataItem.column4 },
{ value: dataItem.column5 },
{ value: dataItem.column6 },
{ value: dataItem.column7 }
]
})
}
}
}
else {
var dataSource = grid.data("kendoGrid").dataSource;
var trs = grid.find('tr');
for (var i = 1; i < dataSource._data.length; i++) {
var dataItem = dataSource._data[i];
rows.push({
cells: [
{ value: dataItem.column1 },
{ value: dataItem.column2 },
{ value: dataItem.column3 },
{ value: dataItem.column4 },
{ value: dataItem.column5 },
{ value: dataItem.column6 },
{ value: dataItem.column7 }
]
})
}
}
var workbook = new kendo.ooxml.Workbook({
sheets: [
{
columns: [
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true }
],
title: "Exported Result",
rows: rows
}
]
});
kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: "ExportedResult" });
}

Jqgrid cascading dropdown

Using jqgrid free latest version 4.15.2
I am trying to make cascading drop down from db.
I tried the sample as posted by #Oleg
jqgrid incorrect select drop down option values in edit box
But this is for older version of jqgrid and does not work fully while using latest version of jqgrid.
var countries = { "UsId": "US", "UkId": "UK" },
statesOfUS = { "AlabamaId": "Alabama", "CaliforniaId": "California", "FloridaId": "Florida", "HawaiiId": "Hawaii" },
statesOfUK = { "LondonId": "London", "OxfordId": "Oxford" },
states = $.extend({}, statesOfUS, statesOfUK),
allCountries = $.extend({"": "All"}, countries),
allStates = $.extend({"": "All"}, states),
// the next maps provide the states by ids to the contries
statesOfCountry = {
"": states,
"UsId": statesOfUS,
"UkId": statesOfUK
},
The entire code can be seen in fiddle below
https://jsfiddle.net/svnL4Lsv/
The issue is during the add form the second dropwdown shows all states instead of showing as per country
Secondly during the edit the second dropdown again shows all states and not as per the row value
Its just when I change the first dropdown does the second dropdown filters and works.
----------Updated
editoptions: {
// value: countries,
dataInit: dataInitApp,
dataEvents: dataEventsApp,
dataUrl: '#Url.Action("GetData", "Home")',
}
Controller code:
public enum Countries
{
USA = 1,
UK = 2
}
public enum State
{
Alabama = 1,
Florida = 2
London = 3
}
public JsonResult GetData()
{
var type = typeof(Helpers.UsersEnum.Countries);
var jsonData = Enum.GetNames(type)
.Select(name => new
{
Id = (int)Enum.Parse(type, name),
Name = name
})
.ToArray();
return Json(jsonData);
}
I call the above to populate my dropdown.
Also below is the json that is returned back:
[0]: {Id=1, Name="USA"}
[1]: {Id=2, Name="UK"}
[0]: {Id=1, Name="Alabama "}
[1]: {Id=2, Name="Florida"}
[2]: {Id=3, Name="London"}
In case of usage free jqGrid you can use a little simplified code
$(function () {
"use strict";
var countries = "usId:US;ukId:UK",
allStates = "alabamaId:Alabama;californiaId:California;floridaId:Florida;hawaiiId:Hawaii;londonId:London;oxfordId:Oxford",
// the next maps provide the states by ids to the countries
statesOfCountry = {
"": allStates,
usId: "alabamaId:Alabama;californiaId:California;floridaId:Florida;hawaiiId:Hawaii",
ukId: "londonId:London;oxfordId:Oxford"
},
mydata = [
{ id: "10", country: "usId", state: "alabamaId", name: "Louise Fletcher" },
{ id: "20", country: "usId", state: "floridaId", name: "Jim Morrison" },
{ id: "30", country: "ukId", state: "londonId", name: "Sherlock Holmes" },
{ id: "40", country: "ukId", state: "oxfordId", name: "Oscar Wilde" }
],
$grid = $("#list"),
changeStateSelect = function (countryId, countryElem) {
// build "state" options based on the selected "country" value
var $select, selectedValues,
$countryElem = $(countryElem),
isInSearchToolbar = $countryElem.parent().parent().parent().parent().hasClass("ui-search-table");
// populate the subset of countries
if (isInSearchToolbar) {
// searching toolbar
$select = $countryElem.closest("tr.ui-search-toolbar")
.find(">th.ui-th-column select#gs_list_state");
} else if ($countryElem.is(".FormElement")) {
// form editing
$select = $countryElem.closest("form.FormGrid")
.find("select#state.FormElement");
} else {
// inline editing
$select = $("select#" + $.jgrid.jqID($countryElem.closest("tr.jqgrow").attr("id")) + "_state");
}
if ($select.length > 0) {
selectedValues = $select.val();
if (isInSearchToolbar) {
$select.html("<option value=\"\">All</option>");
} else {
$select.empty();
}
$.jgrid.fillSelectOptions($select[0], statesOfCountry[countryId], ":", ";", false, selectedValues);
}
},
dataInitCountry = function (elem) {
setTimeout(function () {
$(elem).change();
}, 0);
},
dataEventsCountry = [
{ type: "change", fn: function (e) { changeStateSelect($(e.target).val(), e.target); } },
{ type: "keyup", fn: function (e) { $(e.target).trigger("change"); } }
],
cancelInlineEditingOfOtherRows = function (rowid) {
var $self = $(this), savedRows = $self.jqGrid("getGridParam", "savedRow");
if (savedRows.length > 0 && rowid !== savedRows[0].id) {
$self.jqGrid("restoreRow", savedRows[0].id);
}
};
$grid.jqGrid({
data: mydata,
datatype: "local",
colNames: [ "Name", "Country", "State" ],
colModel: [
{ name: "name", width: 180 },
{ name: "country", formatter: "select", stype: "select", edittype: "select",
searchoptions: {
noFilterText: "Any",
dataInit: dataInitCountry,
dataEvents: dataEventsCountry
},
editoptions: {
value: countries,
dataInit: dataInitCountry,
dataEvents: dataEventsCountry
}},
{ name: "state", formatter: "select", stype: "select", edittype: "select",
editoptions: { value: allStates }, searchoptions: { noFilterText: "Any" } }
],
cmTemplate: { width: 100, editable: true },
onSelectRow: cancelInlineEditingOfOtherRows,
ondblClickRow: function (rowid) {
cancelInlineEditingOfOtherRows.call(this, rowid);
$(this).jqGrid("editRow", rowid);
},
inlineEditing: {
keys: true
},
formEditing: {
onclickPgButtons: function (whichButton, $form, rowid) {
var $self = $(this), $row = $($self.jqGrid("getGridRowById", rowid)), countryId;
if (whichButton === "next") {
$row = $row.next();
} else if (whichButton === "prev") {
$row = $row.prev();
}
if ($row.length > 0) {
countryId = $self.jqGrid("getCell", $row.attr("id"), "country");
changeStateSelect(countryId, $form.find("#country")[0]);
}
},
closeOnEscape: true
},
searching: {
searchOnEnter: true,
defaultSearch: "cn"
},
navOptions: {
del: false,
search: false
},
iconSet: "fontAwesome",
sortname: "name",
sortorder: "desc",
viewrecords: true,
rownumbers: true,
pager: true,
pagerRightWidth: 85, // fix wrapping or right part of the pager
caption: "Demonstrate dependent selects (inline editing on double-click)"
})
.jqGrid("navGrid")
.jqGrid("filterToolbar");
});
see https://jsfiddle.net/OlegKi/svnL4Lsv/3/

Kendo UI grid drag&drop placeholder

I have grid with drag&drop functionality:
var data = [
{ id: 1, text: "text 1", position: 0 },
{ id: 2, text: "text 2", position: 1 },
{ id: 3, text: "text 3", position: 2 }
]
var dataSource = new kendo.data.DataSource({
data: data,
schema: {
model: {
id: "id",
fields: {
id: { type: "number" },
text: { type: "string" },
position: { type: "number" }
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
scrollable: false,
columns: ["id", "text", "position"]
}).data("kendoGrid");
grid.table.kendoDraggable({
filter: "tbody > tr",
group: "gridGroup",
threshold: 100,
hint: function(e) {
return $('<div class="k-grid k-widget"><table><tbody><tr>' + e.html() + '</tr></tbody></table></div>');
}
});
grid.table.kendoDropTarget({
group: "gridGroup",
drop: function(e) {
e.draggable.hint.hide();
var target = dataSource.getByUid($(e.draggable.currentTarget).data("uid")),
dest = $(document.elementFromPoint(e.clientX, e.clientY));
if (dest.is("th")) {
return;
}
dest = dataSource.getByUid(dest.parent().data("uid"));
//not on same item
if (target.get("id") !== dest.get("id")) {
//reorder the items
var tmp = target.get("position");
target.set("position", dest.get("position"));
dest.set("position", tmp);
dataSource.sort({ field: "position", dir: "asc" });
}
}
});
(working example: http://jsfiddle.net/JBeQn/ )
Is it possible to show the placeholder where the row will be dropped? From current implementation it's not obvious. So I would like to make something like this:
http://demos.telerik.com/kendo-ui/sortable/events
or this:
http://jsfiddle.net/bgrins/tzYbU/
In the demo above placeholder is showed and it's quite easy to understand where the row will be dropped.
So any ideas?

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.

Resources