Jqgrid cascading dropdown - jqgrid

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/

Related

jsGrid has 2 headers when inserting is added

Forgive me I am new to using the jsGrid so this might be a stupid problem but...
I have a jsGrid with several columns. One column is a date field. I want to add a date picker instead of the input field for it now.
I added the code for the date picker and ran the code and now the jsGrid has 2 headers. One with the input field for the date and the one below with the date picker. I found that as soon as I add inserting: true that is when the 2 headers show.
Please let me know what I am doing wrong.
Here is my code.
$(function () {
var MyDateField = function (config) {
jsGrid.Field.call(this, config);
};
MyDateField.prototype = new jsGrid.Field({
sorter: function (date1, date2) {
return new Date(date1) - new Date(date2);
},
itemTemplate: function (value) {
return new Date(value).toDateString();
},
insertTemplate: function (value) {
return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() });
},
editTemplate: function (value) {
return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value));
},
insertValue: function () {
return this._insertPicker.datepicker("getDate").toISOString();
},
editValue: function () {
return this._editPicker.datepicker("getDate").toISOString();
}
});
jsGrid.fields.myDateField = MyDateField
$("#jsGrid").jsGrid({
width: "100%",
inserting: true,
filtering: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
rowClass: function (item, itemIndex) {
if (item.DisplayOrder == 1) {
return 'past-due'
}
if (item.DisplayOrder == 2) {
return 'second-notice'
}
pageButtonCount: 5,
controller: controller,
fields: [{
name: "Task Number",
type: "number",
itemTemplate: function (value, item) {
return $("<a>").attr("href", "TaskDetail.aspx?id=" + value).text(value);
},
align: "center"
}, {
name: "Requirement",
type: "text",
itemTemplate: function (value, item) {
return $("<a>").attr("href", "RequirementDetail.aspx?id=" + item.req_id).text(value);
},
width : "350px"
}, {
name: "MERM",
type: "text",
itemTemplate: function (value, item) {
return $("<a>").attr("href", "MERM_Detail.aspx?id=" + item.merm_id).text(value);
}
}, {
name: "Due Date",
type: "myDateField",
width: 80,
align: "center"
}, {
name: "Action Required",
type: "select",
items: actions,
valueField: "name",
textField: "name"
}, {
name: "Workflow Step",
title: "Workflow Step",
type: "select",
align: "center",
items: workflowsteps2,
valueField: "id",
textField: "DisplayName"
}, {
name: "Status",
type: "select",
align: "center",
items: statii2,
valueField: "id",
textField: "DisplayName"
}, {
name: "Importance",
type: "select",
items: importances,
valueField: "id",
textField: "DisplayName",
itemTemplate: function (value, item) {
return $("<div>").addClass(item.Importance == 1 ? 'critical-importance' : item.Importance == 2 ? 'high-importance' : item.Importance == 3 ? 'low-importance' : '').text(item.Importance == 1 ? 'Critical' : item.Importance == 2 ? 'High' : item.Importance == 3 ? 'Low' : '');
}
}, {
visible:false,
name: "Marked Ready for Review Date",
type: "text",
itemTemplate: function (value, item) {
if (value === "NULL") {
return "";
}
return value;
}
}, {
visible:false,
name: "QA Completed Date",
type: "text",
itemTemplate: function (value, item) {
if (value === "NULL") {
return "";
}
return value;
}
}, {
name: "Completed Date",
type: "text",
itemTemplate: function (value, item) {
if (value === "NULL") {
return "";
}
return value;
}
}],
onDataLoaded: function () {
$('#loading').hide();
}
});
});
}
The "Due Date" is the field I am talking about.
Thank you for the help.

jQGrid - "reloadGrid" - Keep Position

I'm trying to 'refresh' or 'reload' a grid and keep the row which has focus after the grid has been reloaded.
I've tried to do it as follows:-
var rowId = $("#dispatch").jqGrid('getGridParam','selrow');
var thisRow = (parseInt(rowId) + parseInt(1));
$("#dispatch").trigger("reloadGrid");
setTimeout(function(){
$("#dispatch").setSelection(thisRow);
}, 151);
But you can see it just from position #1 to the new position.
Is there any other way of reloading the grid and keeping focus position?
Tried:-
// Display Current Jobs
$('#btn-current').bind('click', function() {
$.ajax({
type: 'GET',
url: 'scripts/php/jobs.controller.php',
data: "id=" + "current",
success: function(data){
allButtons.removeClass('active');
$('#btn-current').addClass('active');
$("#dispatch").trigger("reloadGrid", [{current:true}]);
}
});
});
Grid:-
$(function () {
var lastsel2
var rowsToColor = [];
$("#dispatch").jqGrid({
url: 'scripts/xml/jobs.xml',
datatype: "xml",
xmlReader: {
root:"joblist",
row:"job",
repeatitems:false,
},
colNames: ["Time", "Car", "Status", "P", "Pickup", "Zone", "Destination", "Fare", "Name", "Type", "Tel", "Comments", "Account No", "Allow Time", "Tariff", "Email", "Driver Fare", "Driver Extras", "Customer Extras", "Driver", "Driver Comments", "Reference No", "Payment", "From No", "From Street", "From PostCode", "To No", "To Street", "To PostCode", "Account Name", "Flight No", "From Zone No", "To Zone No"],
colModel: [
{ name: "bookingdatetime", width: 55, editable: true },
{ name: "car", width: 45, editable: true },
{ name: "jbmessage", width: 60 },
{ name: "prebooking", width: 10 },
{ name: "pickup", width: 359, editable: true, classes:"grid-col"},
{ name: "zone", width: 50 },
{ name: "dropoff", width: 359, sortable: false, editable: true },
{ name: "customerfare", width: 76, editable: true },
{ name: "passname", width: 100, editable: true },
{ name: "cartype", width: 50, editable: true, },
{ name: "tel", width: 100, editable: true },
{ name: "comments", width: 150 },
{ name: "accountno", hidden: true },
{ name: "allowtime", hidden: true },
{ name: "tarif", hidden: true },
{ name: "emailaddress", hidden: true },
{ name: "driverfare", hidden: true },
{ name: "driverextras", hidden: true },
{ name: "customerextras", hidden: true },
{ name: "driver", hidden: true },
{ name: "comments1", hidden: true },
{ name: "referenceno", hidden: true },
{ name: "payment", hidden: true },
{ name: "fromno", hidden: true },
{ name: "fromstreet", hidden: true },
{ name: "frompostcode", hidden: true },
{ name: "tono", hidden: true },
{ name: "tostreet", hidden: true },
{ name: "topostcode", hidden: true },
{ name: "customer", hidden: true },
{ name: "flightno", hidden: true },
{ name: "fromzoneno", hidden: true },
{ name: "tozoneno", hidden: true }
],
loadComplete: function (){
var rowIds = $('#dispatch').jqGrid('getDataIDs');
for (i = 1; i <= rowIds.length; i++) {//iterate over each row
rowData = $('#dispatch').jqGrid('getRowData', i);
//set background style if Payment = Account
if (rowData['payment'] == 'Acc') {
$('#dispatch').jqGrid('setRowData', i, false, "yellow");
}
if (rowData['payment'] == 'CC') {
$('#dispatch').jqGrid('setRowData', i, false, "purple");
}
if (rowData['cartype'] == 'Est') {
$('#dispatch').jqGrid('setRowData', i, false, "green");
}
if (rowData['cartype'] == '8B' || rowData['cartype'] == 'Bus') {
$('#dispatch').jqGrid('setRowData', i, false, "red");
}
if (rowData['car'] == '00') {
$('#dispatch').jqGrid('setRowData', i, false, "cancel");
}
}
},
pager: "#pager",
loadui: 'disable',
rowNum: 50,
rowList: [10, 20, 30],
sortname: "invid",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
width: null,
shrinkToFit: false,
height: 647,
scrollOffset: 0,
altRows:true,
altclass:'myAltRowClass',
onSelectRow: function (id, status) {
$('#txt-car-number').focus();
$('body').keyup(function (e) {
if (status && e.keyCode == 66 && $("#booking-docket").dialog("isOpen") === false) {
populateDocket();
$("#booking-docket").dialog('open');
}
});
},
gridComplete: function () {
$("#dispatch").setSelection(0, true);
},
});
$("#dispatch").jqGrid('setGridParam', {ondblClickRow: function(rowid,iRow,iCol,e){
populateDocket();
$("#booking-docket").dialog('open');
}});
$("#dispatch").jqGrid('bindKeys');
function populateDocket() {
var rowId =$("#dispatch").jqGrid('getGridParam','selrow');
var rowData = jQuery("#dispatch").getRowData(rowId);
var bookingdatetime = rowData['bookingdatetime'];
var car = rowData['car'];
var fromno = rowData['fromno'];
var fromstreet = rowData['fromstreet'];
var frompostcode = rowData['frompostcode'];
var tono = rowData['tono'];
var tostreet = rowData['tostreet'];
var topostcode = rowData['topostcode'];
var customerfare = rowData['customerfare'];
var passname = rowData['passname'];
var cartype = rowData['cartype'];
var tel = rowData['tel'];
var comments = rowData['comments'];
var accountno = rowData['accountno'];
var allowtime = rowData['allowtime'];
var tariff = rowData['tarif'];
var email = rowData['emailaddress'];
var driverFare = rowData['driverfare'];
var driverExtras = rowData['driverextras'];
var customerExtras = rowData['customerextras'];
var driver = rowData['driver'];
var commentsdrv = rowData['comments1'];
var referenceno = rowData['referenceno'];
var payment = rowData['payment'];
var accountname = rowData['customer'];
var flightno = rowData['flightno'];
var prebook = rowData['prebooking'];
var bookedby = rowData['bookedby'];
var date = bookingdatetime.split(' ');
var hour = date[1].substr(0,2)
var minute = date[1].substr(6,5)
$('#txt-date').val(date[0]);
$('#txt-hour').val(hour);
$('#txt-min').val(minute);
$('#txt-car').val(car);
$('#txt-pickup-hn').val(fromno);
$('#txt-pickup').val(fromstreet);
$('#txt-destination-hn').val(tono);
$('#txt-destination').val(tostreet);
$('#txt-client-fare').val(customerfare);
$('#txt-passenger').val(passname);
$('#txt-cartype').val(cartype);
$('#txt-telephone').val(tel);
$('#txt-general').val(comments);
$('#txt-account').val(accountno);
$('#txt-lead').val(allowtime);
$('#txt-tariff').val(tariff);
$('#txt-email').val(email);
$('#txt-drv-fare').val(driverFare);
$('#txt-account-name').val(accountname);
$('#txt-driver').val(driver);
$('#txt-office').val(commentsdrv);
$('#p-reference-no').html('-'+referenceno+'-');
$('#txt-payment').val(payment);
$('#txt-flight-no').val(flightno);
$('#txt-prebook').val(prebook);
$('#txt-bookedby').val(bookedby);
}
// Navigate Grids
$(document).keypress(function(e) {
if(e.keyCode == 40) { //down arrow
$('#nextElementId').click();
}
if(e.keyCode == 38) { //up arrow
$('#previousElementId').click();
}
});
$(document).keypress(function(e)
{
if(e.keyCode == 38 || e.keyCode == 40) //up/down arrow override
{
var gridArr = $('#dispatch').getDataIDs();
var selrow = $('#dispatch').getGridParam("selrow");
var curr_index = 0;
for(var i = 0; i < gridArr.length; i++)
{
if(gridArr[i]==selrow)
curr_index = i;
}
if(e.keyCode == 38) //up
{
if((curr_index-1)>=0)
$('#dispatch').resetSelection().setSelection(gridArr[curr_index-1],true);
}
if(e.keyCode == 40) //down
{
if((curr_index+1)<gridArr.length)
$('#dispatch').resetSelection().setSelection(gridArr[curr_index+1],true);
}
}
});
XML DATA:-
<?xml version="1.0"?>
<joblist resultcount="100">
<job id="0">
<pickup>26 CHIPPENHAM MEWS W9 2AN</pickup><dropoff>BREWER STREET W1F 0RJ</dropoff><bookingdatetime>14/05/2014 10:29:19</bookingdatetime><car></car><jbmessage></jbmessage><zone>MOUNTAIN</zone><customerfare>12</customerfare><passname>ele</passname><cartype>Car</cartype><tel>07771764901</tel><comments></comments><accountno></accountno><allowtime>10</allowtime><tarif>1</tarif><emailaddress></emailaddress><driverfare>12</driverfare><driverextras>0</driverextras><customerextras>0</customerextras><driver></driver><comments1></comments1><referenceno>221194</referenceno><payment>Cash</payment><fromno>26</fromno><fromstreet>CHIPPENHAM MEWS</fromstreet><frompostcode>W9 2AN</frompostcode><tono></tono><tostreet>BREWER STREET</tostreet><topostcode>W1F 0RJ</topostcode><prebooking>X</prebooking><customer></customer><flightno></flightno><bookedby>SAJJAD</bookedby><fromzoneno>27</fromzoneno><tozoneno>29</tozoneno></job><job id="1"><pickup>7 FOSBURY MEWS W23JE</pickup><dropoff>HEATHROW TER(T5) TW6 2GA</dropoff><bookingdatetime>13/05/2014 20:57:40</bookingdatetime><car>4</car><jbmessage>PAloc</jbmessage><zone>BALDWIN</zone><customerfare>41</customerfare><passname>BLOECKER</passname><cartype>MPV</cartype><tel>07435358308</tel><comments></comments><accountno></accountno><allowtime>15</allowtime><tarif>2</tarif><emailaddress></emailaddress><driverfare>41</driverfare><driverextras>0</driverextras><customerextras>0</customerextras><driver></driver><comments1></comments1><referenceno>220938</referenceno><payment>Cash</payment><fromno>7</fromno><fromstreet>FOSBURY MEWS</fromstreet><frompostcode>W23JE</frompostcode><tono></tono><tostreet>HEATHROW TER(T5)</tostreet><topostcode>TW6 2GA</topostcode><prebooking>X</prebooking><customer></customer><flightno></flightno><bookedby>SHEERAZ</bookedby><fromzoneno>21</fromzoneno><tozoneno>196</tozoneno>
</job>
</joblist>
Instead of usage setSelection inside of setTimeout you need just use additional parameter of reloadGrid: current:true. See the answer for more details.
UPDATED: The code of gridComplete seems be the reason of your problem:
$("#dispatch").setSelection(0, true);
it resets the selection of the grid after reloading to the row with the id="0".
I would strictly recommend you to replace the code of loadComplete to much more effective rowattr callback. See the answer for the corresponding code example.
Additionally you should not bind $('body').keyup on every row selection. In the way you bind (register) more and more new keyup event handles without unbinding the previous one. I'm not sure what you want to do in the part of the code, but you should probably move the code outside of onSelectRow callback.
I don't see any reason to set ondblClickRow with respect of setGridParam after the grid is created. Instead of that you can just include ondblClickRow callback directly in the list of jqGrid option during creating the grid (like you defined loadComplete, onSelectRow and gridComplete callbacks).
I recommend you to use $(this) instead of $('#dispatch') inside of any jqGrid callback.

How to prevent the whole grid from refreshing when a single cell data changes in kendo grid?

While we can use virtualization or paging to speed up refreshing, the whole-grid refresh for each data change is not good at all. Is there a way to avoid this?
This gets worse when multiple data changes in the bound objects, the grid gets refreshed for each change, which is not good either.
function PresonDetails(_contactName, _contactTitle, _country, _companyName) {
Object.defineProperties(this, {
"ContactName": {
get: function () {
return this._contactName;
},
set: function (value) {
this._contactName = value;
},
enumerable: true,
configurable: true
},
"ContactTitle": {
get: function () {
return this._contactTitle;
},
set: function (value) {
this._contactTitle = value;
},
enumerable: true,
configurable: true
},
"Country": {
get: function () {
return this._country;
},
set: function (value) {
this._country = value;
},
enumerable: true,
configurable: true
},
"CompanyName": {
get: function () {
return this._companyName;
},
set: function (value) {
this._companyName = value;
},
enumerable: true,
configurable: true
}
});
this.ContactName = _contactName;
this.ContactTitle = _contactTitle;
this.Country = _country;
this.CompanyName = _companyName;
}
(function () {
var details = [];
details.push(new PresonDetails("ContactName1", "ContactTitle", "USA", "MICro"));
var refresh = window.kendo.ui.Grid.fn.refresh;
window.kendo.ui.Grid.fn.refresh = function () {
alert("Grid Refresh");
refresh.call(this,arguments);
}
var $grid = $('#grid');
$grid.kendoGrid({
scrollable: true,
dataSource: details,
groupable: false,
sortable: false,
editable: true,
columns: [{
field: "ContactName",
title: "Contact Name",
width: 200
}, {
field: "ContactTitle",
title: "Contact Title",
width: 250
}, {
field: "CompanyName",
title: "Company Name"
}, {
field: "Country",
width: 150,
}]
});
})();
here is the demo
Preventing the dataBinding event of the grid will stop the refresh:
funnction avoidRefresh(e) {
e.preventDefault();
}
// stop refresh
grid.bind("dataBinding", avoidRefresh);
// allow refresh
grid.unbind(avoidRefresh);

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);
}

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