How to get field value when edit data in Kendo Ui treelist - kendo-ui

I'm new in Kendo UI,and i have a question. Now i'm use TreeList / Editing and how to auto load value to other field when i edit value to first field ?
example:
1.serial number: 123456789
2.name : test
when i edit serial number 123456789 to first field and auto load name to second field.

To set the value of column B based on change made to a column A, you need to edit the model bound to the tree list. For this do the following:-
Handle edit event of the tree list. On this save the model to a
local variable.
Add an editor
template
to column A. On the select event set the value of model.
Below is a working code snippet:-
<div id="treelist"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service";
var model= null;
var employeesData=[{"EmployeeId":101,"FirstName":"Daryl","LastName":"Sweeney"},
{"EmployeeId":202,"FirstName":"Guy","LastName":"Wooten"},
{"EmployeeId":303,"FirstName":"Priscilla","LastName":"Frank"},
{"EmployeeId":404,"FirstName":"Ursula","LastName":"Holmes"},
{"EmployeeId":505,"FirstName":"Anika","LastName":"Vega"}];
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/EmployeeDirectory/All",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
schema: {
model: {
id: "EmployeeId",
parentId: "ReportsTo",
fields: {
EmployeeId: { type: "number", nullable: false },
ReportsTo: { nullable: true, type: "number" },
FirstName: { validation: { required: true } },
HireDate: { type: "date" },
Phone: { type: "string" },
HireDate: { type: "date" },
BirthDate: { type: "date" },
Extension: { type: "number", validation: { min: 0} },
Position: { type: "string" }
},
expanded: true
}
}
});
$("#treelist").kendoTreeList({
dataSource: dataSource,
toolbar: [ "create", "save", "cancel" ],
editable: "incell",
height: 540,
dataBound: function (e) {
var items = e.sender.items();
for (var i = 0; i < items.length; i++) {
var dataItem = e.sender.dataItem(items[i]);
var row = $(items[i]);
if (dataItem.isNew()) {
row.find("[data-command='createchild']").hide();
}
else {
row.find("[data-command='createchild']").show();
}
}
},
edit: function(e) {
model = e.model;
},
columns: [{
field: "EmployeeId",
expandable: true,
title: "Serial Number",
width: 180,
editor: function(container, options) {
// create an input element
var input = $("<input/>");
// set its name to the field to which the column is bound ('lastName' in this case)
input.attr("name", options.field);
// append it to the container
input.appendTo(container);
// initialize a Kendo UI AutoComplete
input.kendoAutoComplete({
dataTextField: "EmployeeId",
dataSource: employeesData,
select: function(e) {
if(model !=null){
model.FirstName = e.dataItem.FirstName;
model.LastName = e.dataItem.LastName;
}
}
});
}
},
{ field: "FirstName", title: "First Name", width: 100 },
{ field: "LastName", title: "Last Name", width: 100 },
{ field: "Position", width: 100 },
{ field: "Phone", title: "Phone", width: 100 },
{ field: "Extension", title: "Ext", format: "{0:#}", width: 100 },
{ command: [{name: "createchild", text: "Add child"},"destroy" ], width: 240 }]
});
});
</script>

You can trigger your function when the row is being saved or when the edit field is being changed. Take a look at the list of events here and choose when exactly you want to make the changes. https://demos.telerik.com/kendo-ui/treelist/events
here is a example how to all a function when saving the changes: https://docs.telerik.com/kendo-ui/api/javascript/ui/treelist/methods/saverow
I´m not sure witch edit method you are using (inline, inCell or Popup edit mode) each method can use events like saveRow, beforeEdit...
Check all the events documentation here: https://docs.telerik.com/kendo-ui/api/javascript/ui/treelist#events

Related

How to get value id from dataSource by row Kendo UI Grid

Help me code How to get value id from dataSource by row and change to current value default (1)
in line: var date = dataSource.get(1);
console.log(date.ProductName)
My full source:
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
selectable: true,
pageable: true,
height: 550,
toolbar: ["create"],
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "120px" },
{ field: "UnitsInStock", title:"Units In Stock", width: "120px" },
{ field: "Discontinued", width: "120px", editor: customBoolEditor },
{ command: ["edit", "destroy"], title: " ", width: "250px" }],
editable: "inline",
edit: function () {
var date = dataSource.get(1);
console.log(date.ProductName)
}
});
});
</script>
Now, when click edit, all rows only get fields of id 1. I want corresponding id instead of the default id 1.
edit
Fired when the user edits or creates a data item.
The event handler function context (available via the this keyword)
will be set to the widget instance.
EVENT DATA
e.container jQuery The jQuery object of the edit container
element, which wraps the editing UI. Depending on the Grid edit mode,
the container is different:
"incell" edit mode - the container element is a table cell
"inline" edit mode - the container is a table row
"popup" edit mode - the container is a Kendo UI Window element, which provides an easy way to obtain a reference to the Window widget object, e.g. to attach additional events.
e.model kendo.data.Model The data item which is
going to be edited. Use its isNew method to check if the data item is
new (created) or not (edited).
e.sender kendo.ui.Grid The widget instance which fired the event.
$("#grid").kendoGrid({
columns: [
{ field: "id" },
{ field: "name" },
{ field: "age" },
{ command: "edit" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: {
id: "id",
fields: {
"id": { type: "number" }
}
}
}
},
editable: "popup",
toolbar:["create"],
edit: function(e) {
console.log(e.model.id);
console.log(e.model.name);
}
});
Working example: edit event
Documentation: grid edit event

Empty column after DataSource Query in Kendo

After making a call to DataSource.Query(), I am unable to call grid.setOption() function. If I do, it returns just an empty grid.
I have searched through several forums but no luck so far.
Just calling setOption works as intended in the grid.
this.grid.setOptions({scrollable: true, autoBind: true});
But when I make a call to query function and then call setOption, it loads an empty grid.
this.jobKendoGrid.dataSource.query({
sort: sort,
filter: filter,
pageSize: this.jobKendoGrid.dataSource.pageSize(),
page: 1
})
I think after making dataSource.Query call, the remote call is being disconnected. Guess that's why I am unable to call setOption, but how can I connect back to remote data source?
PS: Edit
The reason I want to call setOption again, is that I have a toolbar option in every grid that I can do "FitToScreen". This option will shink all columns into the screen.
public fitToScreen() {
for (var i = 0; i < this.grid.columns.length; i++) {
if (this.grid.columns[i].title && this.grid.columns[i].title != "Edit" && this.grid.columns[i].title != " ") {
// console.log(this.grid.columns[i].width);
delete this.grid.columns[i].width;
}
}
//setOption Call
this.grid.setOptions({ scrollable: true });
// https://www.telerik.com/forums/grid-setoptions-causes-empty-grid
if (this.grid.options.autoBind === false) {
this.grid.refresh();
}
}
Found a similar query on the grid forum. One of the answers suggested using getOptions() followed by setOptions() doing that resolves the issue.
<div id="example">
<div id="grid"></div>
<button onclick="filterGrid()">Filter Grid</button>
<script>
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
height: 550,
filterable: {extra: false, mode: "row"},
sortable: true,
pageable: true,
columns: [{
field:"OrderID",
filterable: false
},
"Freight",
{
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name", width: 200
}, {
field: "ShipCity",
title: "Ship City", width: 200
}
]
});
});
function filterGrid()
{
var grid = $("#grid").data("kendoGrid");
var sort= { field: "Freight", dir: "desc" };
var filter ={ field: "Freight", operator: "gte", value: 100 };
grid.dataSource.query({
sort: sort,
filter: filter,
pageSize: grid.dataSource.pageSize(),
page: 1
});
fitToScreen();
}
function fitToScreen()
{
console.log("fitToScreen");
var grid = $("#grid").data("kendoGrid");
for (var i = 0; i < grid.columns.length; i++) {
if (grid.columns[i].title && grid.columns[i].title != "Edit" && grid.columns[i].title != " ") {
delete grid.columns[i].width;
}
}
var currOpt = grid.getOptions();
//Check values of options you want to set
console.log(currOpt.sortable);
//setOptions call
grid.setOptions(currOpt);
//refresh call
grid.refresh();
}
</script>
</div>

How I write a dynamic URL in kendo UI DataSource like "update/{id}"

I have a web API. In that I wrote a update method. But it need to id of the table row to update to the row.
I use a grid to show data and use a toolbar to edit the row.
My question is how I pass that id to the update.
Can someone guide me ??
update: function(options) {
$.ajax( {
url: function(data) { return "updateUsuarios/"+data.Id,
dataType: "json",
.....
Well i suggest you, explain more your question, but i think this examples could help , if you have a toolbar as a template like this:
<script type="text/x-kendo-template" id="template">
<div class="toolbar">
<button type="button" id="update">Update</button>
</div>
</script>
You "grid" need the attr "toolbar"
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
filterable:true,
toolbar: kendo.template($("#template").html()),
columns: [
{ field:"username", title: "Username" , width: "120px" },
{ field: "nombre", title:"Nombre", width: "120px" },
{ field: "apellido", title:"Apellido", width: "120px" },
{ field: "ci", title:"Documento de Identidad", width: "120px" },
{ field: "email", title:"Direccion de Correo", width: "120px" },
{ field: "activo",title:"Estatus", width: "120px" },
{ field: "fecha_caducidad",title:"Fin Demo", width: "120px",template: "#= kendo.toString(kendo.parseDate(fecha_caducidad, 'yyyy-MM-dd'), 'MM/dd/yyyy') #" },
{ field: "licencia_status",title:" ", width: "40px",template:'<img src="assets/images/#:data.licencia_status#.png"/>' },
{ command: ["edit"], title: " ", width: "120px" }],
editable: "popup",
dataBound: function () {
var rows = this.items();
$(rows).each(function () {
var index = $(this).index() + 1;
var rowLabel = $(this).find(".row-number");
$(rowLabel).html(index);
});
},
selectable: true
});
So,you can configure a kendo button and add functionality in the event click:
$("#update").kendoButton({
click: function(){
//Here you will have the selected row
var self=$('#grid').data('kendoGrid')
var index = self.items().index(self.select());
var rowActual= self.dataSource.data()[index];
rowActual=self.dataItem(self.select());
if(rowActual==undefined || rowActual ==null) {
alert("No row selected");
}else{
$.ajax({
type: "POST",
url: "update",
data: {
id:rowActual.id
},
dataType: 'json',
success: function (data) {
},
error: function(){
}
});
}
}
});
and send in the ajax the row id, but if you are update the row with the inline edition you could try with a datasource like this
dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax( {
url: "readUsuarios",
dataType: "json",
success: function(result) {
options.success(result);
}
});
},
update: function(options) {
$.ajax( {
url: "updateUsuarios",
dataType: "json",
data: {
models: kendo.stringify(options.data.models)
},
success: function(data) {
// response server;
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "id",
fields: {
username: { editable: false, nullable: true },
nombre: { validation: { required: true } },
apellido: { type: "string", validation: { required: true} },
ci: { type: "string", validation: { required: true} },
email: { type: "string", validation: { required: true } },
activo: { type: "boolean",editable: false },
fecha_caducidad: { type: "date" },
licencia_status:{editable: false}
}
}
}
});
I hope this help!

Kendo UI grid (inline edit) update and cancel not working

i create grid with data by javascript. when i click edit button at first time on any row and click update button. values in first row are null and then i edit other row i can't update or cancel, both button are not working.
when i refresh then click edit and then click cancel that row has removed i don't know why?
What's happend? How to fix?
Data
var detail = new Array();
for (var i = 1; i < 6; i++) {
detail.push({
Score: i,
Condition: 0,
ValueStart: 0,
ValueEnd: 0,
});
}
Grid
for (var i = 0; i < 3; i++) {
$("#GridScoreRangeContent").append("<div id='scoreRangeGrid_"+i+"'></div>");
$("#scoreRangeGrid_"+i).kendoGrid({
dataSource: {
data: detail,
batch: true,
schema: {
model: {
fields: {
Score: { editable: false },
Condition: { defaultValue: { Value: 1, Text: "Less than" }, validation: { required: true } },
ValueStart: { type: "number", validation: { required: true, min: 1 } },
ValueEnd: { type: "number", validation: { required: true, min: 1 } },
}
}
}
},
columns: [{ field: "Score", title: "Score" }},
{ field: "Condition", title: "Condition", editor: ScoreRangeDropDownList, template: "#=Condition#" },
{ field: "ValueStart", title: "Start" },
{ field: "ValueEnd", title: "End" },
{ command: ["edit", "destroy"], title: " ", width: "180px" }
],
editable: "inline"
});
}
Load Dropdownlist
function ScoreRangeDropDownList(container, options) {
$.ajax({
url: GetUrl("Admin/Appr/LoadDropdownlist"),
type: 'post',
dataType: 'json',
contentType: 'application/json',
traditional: true,
cache: false,
success: function (data) {
$('<input required data-text-field="Text" data-value-field="Value" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: data,
dataTextField: "Text",
dataValueField: "Value",
});
}
});
}
Kendo seems to rely on a model ID when saving/updating. So in your dataSource, you have to specify an id:
model: {
id: "Id",
fields: {
Id: { type: "number" },
Score: { editable: false },
Condition: { defaultValue: { Value: 1, Text: "Less than" }, validation: { required: true } },
ValueStart: { type: "number", validation: { required: true, min: 1 } },
ValueEnd: { type: "number", validation: { required: true, min: 1 } },
}
}
What dmathisen is suggesting is definitely important but in addition it is important that the <input/> you create has a name attribute equal to the name of the column. You can use the value of options.field again as in the code from the Kendo Demos page example:
// create an input element
var input = $("<input/>");
// set its 'name' to the field to which the column is bound
input.attr("name", options.field);
// append it to the container
input.appendTo(container);
// initialize a Kendo UI Widget
input.kendoDropDownList({
.
.

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

Resources