jsGrid has 2 headers when inserting is added - jsgrid

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.

Related

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/

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.

KendoUI Grid: Non-editable column?

http://jsfiddle.net/bhoff/ZCyPx/50/
$("#grid").kendoGrid({
dataSource:{
data:entries,
schema:{
parse:function (response) {
$.each(response, function (idx, elem) {
if (elem.time && typeof elem.time === "string") {
elem.time = kendo.parseDate(elem.time, "HH:mm:ss");
}
if (elem.datetime && typeof elem.datetime === "string") {
elem.datetime = kendo.parseDate(elem.datetime, "HH:mm:ss");
}
});
return response;
}
}
},
columns:[
{ command: [ "edit" ] },
{ field:"type", title:"Cash Transation Type" },
{ field:"begintime", title:"Begin Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
{ field:"endtime", title:"End Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
],
editable:"inline",
navigatable:true
});
Based on my example how do I stop the user from editing my "Cash Transation Type" column?
Does it have something to do with this -> editable:"inline" ?
look here
you need to set in the datasource
<script>
var dataSource = new kendo.data.DataSource({
schema: {
model: {
id: "ProductID",
fields: {
ProductID: {
//this field will not be editable (default value is true)
editable: false,
// a defaultValue will not be assigned (default value is false)
nullable: true
},
ProductName: {
//set validation rules
validation: { required: true }
},
UnitPrice: {
//data type of the field {Number|String|Boolean|Date} default is String
type: "number",
// used when new model is created
defaultValue: 42,
validation: { required: true, min: 1 }
}
}
}
}
});
</script>
You would normally set this on your DataSource on the schema.model.fields.
var data = new kendo.data.DataSource({
schema: {
model: {
fields: {
type: { editable: "false" }
Add editable in the field you do not want to enable Edit,
columns:[
{ command: [ "edit" ] },
{ field:"type", title:"Cash Transation Type", editable: false },
{ field:"begintime", title:"Begin Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
{ field:"endtime", title:"End Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
],
editable:"inline",
navigatable:true
});

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