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
});
Related
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.
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.
Given below kendo dataSource which is calling API though services.
It is difficult to identify whether sorting or filtering event is triggered.
var dataSource = new kendo.data.DataSource({
transport: {
// read : "/scripts/data/products/categoryLabel.json",
read : function(options){
// alert(options.data.page + "-" + options.data.pageSize);
console.log("Read options : " , options);
var order_by;
if (options.data.sort) {
if (options.data.sort.length > 0) {
var sortField = options.data.sort[0].field;
if (options.data.sort[0].dir == 'asc') {
var sortOrder = '';
}
else if (options.data.sort[0].dir == 'desc') {
var sortOrder = '-';
};
order_by = sortOrder + sortField;
}
}
if (options.data && options.data.filter && options.data.filter.filters) {
config ={
value: options.data.filter.filters[0].value,
field: options.data.filter.filters[0].field,
accountId: $scope.model.adAccount.accounts.selected.aa_id,
category_id : null,
};
console.log("input: ", options.data.filter.filters[0])
}
Campaignlabel.fetchCategorycampaign(config, order_by, options.data.page, options.data.pageSize).success(function (fetchCampaignlabel) {
$scope.model.totalCount = fetchCampaignlabel.count;
options.columns = $scope.model.columns;
options.success(fetchCampaignlabel.results);
// config = null;
}).error(function (fetchCampaignlabel) {
options.error(fetchCampaignlabel.results);
});
},
},
pageable : true,
pageSize:50,
serverPaging: true,
reorderable: true,
sortable :true,
page : 1,
serverFiltering: true,
serverSorting: true,
schema: {
total: function (result) {
result = result.data || result;
return $scope.model.totalCount;
},
model: {
id : "campaign_id",
fields: {
Select : {type : "boolean"},
category: { editable: false, type: 'number'},
campaign_id: { editable: false, type: 'number'},
name: { editable: false, type : "string" },
objective: { editable: false, type : "string" },
status: { editable: false, type : "string" },
category_name: { editable: false },
start_time : { editable: false, type: "date"},
}
}
},
});
Please suggest any way to identify filter or sorting event here.
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);
}
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.