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>
Related
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
I am a beginner working on Kendo Grid. I wanted to load the data on demand in the grid, like :
I set the page size to 10, when a user scrolls down to 10 rows, the
grid should retrieve next 10 rows from database and display it on
demand.To do this, I changed "scrollable: true" to "scrollable: {virtual: true}". But this disables scrolling in the grid.
$scope.source = new kendo.data.DataSource({
batch: true,
group: getDSGroup(),
transport: {
read: userSvc.getUserList,
update: _dataUpdateItem
},
error: function(e) {
ngDialog.openConfirm({
template: 'httpErrorDialogId',
className: 'ngdialog-theme-default',
data: {
'status': e.status,
'message': e.errorThrown
}
});
},
schema: {
parse: function(data) {
$rootScope.$log.log("User list was fetched.");
if ($rootScope.sysSettings.userMgr_serverPaging)
return data;
for (var i = 0; i < data.items.length; i++) {
data.items[i].letter = data.items[i].lastName.substr(0, 1).toUpperCase();
if (data.items[i].departmentName == null) data.items[i].departmentName = $rootScope.$translate.instant("Unassigned");
if (data.items[i].userGroupName == null) data.items[i].userGroupName = $rootScope.$translate.instant("Unassigned");
}
return data;
},
model: {
id: "id"
},
groups: "groups",
total: "totalItems",
data: "items"
},
filter: getDSFilter(),
sort: getDSSort(),
pageSize: $rootScope.sysSettings.userMgr_serverPaging ? 10 : 0,
serverGrouping: $rootScope.sysSettings.userMgr_serverPaging,
serverPaging: true,
serverSorting: $rootScope.sysSettings.userMgr_serverPaging,
serverFiltering: $rootScope.sysSettings.userMgr_serverPaging
});
$scope.userListOptions = {
//sortable: true,
groupable: true,
selectable: false,
//pageable: true,
scrollable: {
virtual: true
},
//dataBound: function() {
// this.expandRow(this.tbody.find("tr.k-master-row").first());
//},
columns: [{
field: "firstName",
template: kendo.template($("#tpl-UserItem").html())
}, {
field: "letter",
hidden: true,
groupHeaderTemplate: "#= value #"
}]
};
$scope.isEndlessScroll = function() {
return $rootScope.sysSettings.userMgr_serverPaging;
};
If your grid is is being created while is invisible, the connfiguration is a bit diffrent.
http://docs.kendoui.com/getting-started/web/grid/walkthrough#initializing-the-grid-inside-a-hidden-container
hope this help
I am not able to get the following to call the web service function. It has something to do with the ParameterMap since if I call a function that does not need parameters (Meditech_MeditechSearchResultsTEST) then I get results. I have logging set up on the Meditech_MeditechSearchResults web service function and can tell it never gets called.
function GetQuery() {
var SearchText;
var URLLink;
SearchText = document.getElementById('QueryID').value;
var FilterSelected;
FilterSelected = document.getElementById('ArchivedResultsSelect').value;
URLLink = URL + 'Meditech_MeditechSearchResults';
var CurrPage = 1;
var Pagesize =10;
try {
if (SearchText != '') {
$(document).ready(function () {
$("#grid").kendoGrid({
attributes: {
"class": "SearchControls"
},
dataSource: {
pageSize: Pagesize,
transport: {
read: {
url: URLLink,
type: "GET",
dataType: "jsonp",
}
},
type: {
data: "odata"
},
parameterMap: function (options) {
var parameters = {
Search: FormatJSONString(SearchText),
FilterValue: FilterSelected,
CurrentPage: CurrPage,
PageSize: Pagesize
}
return parameters;
},
},
columns: [{
field: "View",
title: "",
width: "30px",
align: "center",
template: kendo.template($("#view-template").html())
},
{
field: "Results",
title: "Results",
width: "800px",
template: kendo.template($("#result-template").html())
},
{
field: "Rank",
title: "Rank",
width: "40px",
},
],
height: 500,
width: 900,
scrollable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
error: function(e) {
alert(e.errors);
},
});
});
}
else { alert('Please enter a search text.') }
}
catch(ex) {
alert(ex.description);
}
}
The parameterMap option is part of the transport configuration. Try putting it there. Right now it is ignored.
Here is my MVC view code :-
<div id="reportsDb">
<div id="grid"></div>
<script type="text/x-kendo-template" id="template">
<div class="toolbar" id="template" >
<label class="Status-label" for="Status">Show reports by status:</label>
<input type="search" id="Status" style="width: 150px"/>
</div>
</script>
<script>
$(document).ready(function () {
var path = ""
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "#Url.Action("Report_Read", "Report")",
dataType: "json",
type: "Get",
contentType: "application/json"
}
},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 10,
schema: {
model: {
id: "RequestId",
fields: {
IPAddress: { type: "string" },
RequestQuetime: { type: "date" },
RequestPicktime: { type: "date" },
RequestRespondTime: { type: "date" },
StatusType: { type: "string" },
RequestTimeDifference: { type: "datetime", format: "{0:hh:mm:ss}" },
RequestPickDifference: { type: "datetime", format: "{0:hh:mm:ss}" }
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
sortable: true,
pageable: true,
filterable: {
extra: false,
operators: {
string: {
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to"
}
}
},
toolbar: kendo.template($("#template").html()),
height: 430,
columns: [
{ field: "IPAddress", title: "IP address", width: 100, filterable: true },
{ field: "RequestQuetime", title: "Que time", width: 100, filterable: false },
{ field: "RequestPicktime", title: "Pick time", width: 110, filterable: false },
{ field: "RequestRespondTime", title: "Respond time", width: 100, filterable: false },
{ field: "StatusType", title: "status", width: 110, filterable: { ui: statusFilter } },
{ field: "RequestTimeDifference", title: "Time difference", width: 110, filterable: false },
{ field: "RequestPickDifference", title: "Pick difference", width: 110, filterable: false }
]
});
function statusFilter(element) {
element.kendoDropDownList({
dataSource: {
transport: {
read: {
url: "#Url.Action("RequestStatus_Read", "Report")",
dataType: "json",
type: "Get",
contentType: "application/json"
}
}
},
dataTextField: "Text",
dataValueField: "Value",
optionLabel: "--Select Value--"
});
}
});
</script>
</div>
And below is the Action Method of controller :-
public ActionResult Report_Read()
{
return Json(_oRepository.GetReports().ToList(), JsonRequestBehavior.AllowGet);
}
I want to apply filtering on StatusType filed and for that I have bound this filed with dropdownlist.
And my problem is when I am trying to do filtering by selecting one of the status from download its doing nothing.
I am working according to this example:
http://demos.telerik.com/kendo-ui/grid/filter-menu-customization
From your code, everything seems fine except the Controller Read Action. Now if the controller is being called when you apply filter from the view on Grid then the only change required on your side is below:
public JsonResult Report_Read([DataSourceRequest] DataSourceRequest request)
{
return Json(_oRepository.GetReports().ToList().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
EDIT:
If you don't use Kendo.MVC then you have two option to filtering:
Option 1: Client side filtering
-> You will need to get all the data at read time so when the filtering is applied you have all the data, which is best option if the data source is not large as it saves unwanted controller requests for filtering.
-> First think you need do is subscirbe to filterMenuInit() of grid and add the below Script for client side filtering.
Code:
filterMenuInit: function(e) {
if (e.field == "name") {
alert("apply Filter");
var filter = []
... // Generate filters
grid.dataSource.filter(filters);
}
}
For detailed example: Extact from Kendo Examples
Option 2: Server side filtering
-> I don't have much idea about it, but whilst I was searching for my options to filtering I had came across the below Question which was good but a bit complex for my application. But I think you can use it.
JS Fiddle Sample
Please refer below Link for detailed explanation.
Reference: JS Kendo UI Grid Options
Check your rendered html for string you have in td and string you are filtering
Look if your td has any other code than the string you are trying to filter. If the case is there is some other html code inside td like a span or a div, then you have to refactor your code to make sure you have content only in td.
Make sure you trim your string inside td.
Try contains instead of equal to. if this works them the issue should be extran text/html or triming.
function applyFilter() {
var filters = [], item_filters = [], brand_filters = [], invoice_id = null;
var item_nested_filter = { logic: 'or', filters: item_filters };
var brand_nested_filter = { logic: 'or', filters: brand_filters };
var gridData = $("#invoicelistgrid").data("kendoGrid");
var invoiceId = $("#invoiceidsearch").data("kendoDropDownList").value();
var itemId = $("#itemsearch").data("kendoDropDownList").value();
var brandId = $("#brandsearch").data("kendoDropDownList").value();
var partyId = $("#party-dropdown").data("kendoDropDownList").value();
if (partyId !== "") {
filters.push({ field: "party_id", operator: "eq", value: parseInt(partyId) });
}
if (invoiceId !== "") {
filters.push({ field: "invoice_id", operator: "eq", value: parseInt(invoiceId) });
}
if (itemId !== "") {
for (var i = 0; i < gridData.dataSource._data.length; i++) {
var data = gridData.dataSource._data[i].tb_invoice_lines;
for (var j = 0; j < data.length; j++) {
if (parseInt(itemId) === parseInt(data[j].item_id)) {
item_filters.push({ field: "invoice_id", operator: "eq", value: parseInt(data[j].invoice_id) });
} else {
invoice_id = data[j].invoice_id;
}
}
}
if (item_filters.length > 0) {
filters.push(item_nested_filter);
} else {
filters.push({ field: "invoice_id", operator: "eq", value: parseInt(invoice_id) });
}
}
if (brandId !== "") {
for (var k = 0; k < gridData.dataSource._data.length; k++) {
var brand_data = gridData.dataSource._data[k].tb_invoice_lines;
for (var l = 0; l < brand_data.length; l++) {
console.log("Grid item id = " + brand_data[l].brand_id);
if (parseInt(brandId) === parseInt(brand_data[l].brand_id)) {
brand_filters.push({
field: "invoice_id",
operator: "eq",
value: parseInt(brand_data[l].invoice_id)
});
} else {
invoice_id = brand_data[l].invoice_id;
}
}
}
if (brand_filters.length > 0) {
filters.push(brand_nested_filter);
} else {
filters.push({ field: "invoice_id", operator: "eq", value: parseInt(invoice_id) });
}
}
console.log(filters);
gridData.dataSource.filter({
logic: "and",
filters: filters
});
}
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.