Aurelia-Kendo grid - multiple unnecessary request for datasource - kendo-ui

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)

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>

Kendo grid virtual scrolling broken/not fetching data

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

Filter of Kendo UI Grid is not executed for specified column

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

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({
.
.

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