Kendo grid virtual scrolling broken/not fetching data - kendo-ui

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

Related

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>

Aurelia-Kendo grid - multiple unnecessary request for datasource

I have the following html-page: (part of page)
<ak-multiselect k-data-text-field="text"
k-data-value-field="value" k-value.two-way="selectPaymentType" k-data-source.bind="dataPaymentType"
</ak-multiselect>
<br/>
<ak-multiselect k-data-text-field="text"
k-data-value-field="value" k-value.two-way="selectPaymentResult" k-data-source.bind="dataPaymentResult"
</ak-multiselect>
<br/>
<button ak-button="k-icon: ungroup; k-widget.bind: button" k-on-click.delegate="GetTransaction()">Get Transactions</button>
<br/>
<div ref="gridTransaction"></div>
This is my viewmodel:
export class Transaction {
selectPaymentType;
selectPaymentResult;
gridTransaction;
dataPaymentType = [
{ text: 'Mobile Payment', value: '0' },
{ text: 'Card Present Payment', value: '1' },
{ text: 'Cash Payment', value: '2' }
]
dataPaymentResult = [
{ text: 'Pending', value: '0' },
{ text: 'Approved', value: '1' },
{ text: 'Declined', value: '2' }
]
buildTransactionFilters() {
var filtersTotal = [];
var filtersPaymentType = [];
var selectPaymentType = this.selectPaymentType;
if (selectPaymentType != null && selectPaymentType.length > 0) {
selectPaymentType.forEach(function (item, i, dataItems) {
filtersPaymentType.push({
field: "paymentType",
operator: "eq",
value: item
});
});
}
var filterPaymentType = {
logic: "or",
filters: filtersPaymentType
};
var filtersPaymentResult = [];
var selectPaymentResult = this.selectPaymentResult;
if (selectPaymentResult != null && selectResult.length > 0) {
selectPaymentResult.forEach(function (item, i, dataItems) {
filtersPaymentResult.push({
field: "result",
operator: "eq",
value: item
});
});
}
var filterPaymentResult = {
logic: "or",
filters: filtersPaymentesult
};
if (filtersPaymentType.length > 0)
filtersTotal.push(filterPaymentType);
if (filtersPaymentResult.length > 0)
filtersTotal.push(filterPaymentResult);
return {
logic: "and",
filters: filtersTotal
};
}
GetTransaction() {
var filters = this.buildTransactionFilters();
var datasourceTransaction = new kendo.data.DataSource({
type: "json",
transport: {
read: {
type: "POST",
contentType: "application/json; charset=utf-8",
url: "api/getTransaction",
cache: false
},
parameterMap(data, operation) {
if (data.models) {
return JSON.stringify({ products: data.models });
} else if (operation === "read") {
return JSON.stringify(data);
}
}
},
filter: filters,
schema: { data: "data", total: "total", aggregates: "aggregates"},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 10
})
var $grid = $(this.gridVM).kendoGrid({
dataSource: datasourceTransaction,
pageable: { refresh: true, pageSizes: true, buttonCount: 5 },
scrollable: true,
sortable: true,
columns: [{ field: "publicId", title: "Public Id", filterable: false},
{ field: "initiated", title: "Initiated", filterable: false, type: "datetime"},
{field: "total", title: "Total", filterable: false}
]
}).data("kendoGrid");
}
}
I choose the necessary filtering, press on the button and see the correct data. Then I change filter and press on the button - the data is correct again. But if I change page number or record number on the count, I can see in Network all my previous requests. As result - I see in grid the faster response from my previous requests (with different filters). Quantity of previous requests - how many times I have clicked on the button.
How I can fixed it and get data only from last request?
Use ak-grid for your grid and don't initialize it the jquery way. Take a look at the documentation: https://aurelia-ui-toolkits.github.io/demo-kendo/#/samples/grid-basic-use
Define the dataSource in your viewmodel once instead of creating a new one after each click on the button. Just change the filter of te dataSource in your getTransactions method (http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#methods-filter)

Kendo Grid Search ParameterMap

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.

Kendo Grid Will not populate with server side data

I cannot get Kendo Grid to populate from server side data.
I have a grid builder function as as follows:
var build = function (carrier, date) {
var urlBase = 'my base url';
var datasource = new kendo.data.DataSource({
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
schema: {
model: {
id: 'Id',
fields: {
StatementDate: { type: "string", editable: false },
CobDate: { type: "string", editable: false },
//lots more fields
Status: { type: "string", editable: false },
Matched: { type: "boolean", editable: true }
}
}
},
transport: {
read: function (options) {
var address = urlBase + '/' + carrier + '/' + date;
$.ajax({
url: address,
type: "POST",
data: JSON.stringify(options.data),
contentType: "application/json",
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
});
},
//update function omitted
parameterMap: function (data, operation) {
if (operation == "read") {
return JSON.stringify(data)
}
},
change: function (e) {
var data = this.data();
console.log(data.length); // displays "77"
}
}
});
return datasource;
};
return {
build: build
}
Grid Definition
elem.kendoGrid({
columns: [
{ field: "StatementDate", title: "State Date", width: 125 },
{ field: "CobDate", title: "COB Date", width: 100 },
//lots more fields
{ command: ["edit"], title: " ", width: "85px"}],
resizable: true,
sortable: true,
editable: "inline",
columnMenu: true,
filterable: true,
reorderable: true,
pageable: true,
selectable: "multiple",
change: this.onSelectedRecordChanged,
toolbar: kendo.template($('#' + templateName).html()),
scrollable: {
virtual: true
},
height: 800
});
I trigger the update via a button click. When I look at the response I see the data. Looks good but the grid will not show the data. It has previously worked fine when data was completely client side.
If I break point on the AJAX call back. I see the correct results.
The grid is bound with data bind. The datasource is a property on a viewmodel.
<div id="grid" data-bind="source: dataSource"></div>
At the start of the app. I create view model
var viewModel= kendo.observable(new GridViewModel(...
and bind
kendo.bind($('#grid'), viewModel);
If I look at the datasource attached to the grid, I see data for the page as expected
This has previously worked fine when data was client side.
I have tried using read() on datasource, and refresh() method on grid. Neither seems to work.
Example response content from server
{"Data":[{"Id": //lots more fields, 20 records],"Total":90375,"AggregateResults":null,"Errors":null}
Any help very much appreciated.
I found the cause in datasource schema missing
{ data: 'Data', total: 'Total' }

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