How to get the pop up for kendo drop down if data is not matched - kendo-ui

I can able to filer the matched data using filter button.How to get the popup window if there is no matched data after clicking the filter data.Present If there is no matched data the table is showing empty instead of that how to rise a pop to tell no matched data to filter
// Set up information window
$("#filter-msg").kendoWindow({
modal: true,
visible: false
});
// Set up date pickers
$("#datetimepicker1").kendoDatePicker({});
$("#datetimepicker2").kendoDatePicker({});
// Set up DDL
var categories = $("#categories").kendoDropDownList({
optionLabel: "Select category...",
dataTextField: "CategoryName",
dataValueField: "CategoryID",
dataSource: {
type: "odata",
serverFiltering: true,
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Categories"
}
}
}).data("kendoDropDownList");
var products = $("#products").kendoDropDownList({
autoBind: false,
cascadeFrom: "categories",
optionLabel: "Select product...",
dataTextField: "ProductName",
dataValueField: "ProductID",
dataSource: {
type: "odata",
serverFiltering: true,
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Products"
}
}
}).data("kendoDropDownList");
var orders = $("#orders").kendoDropDownList({
autoBind: false,
cascadeFrom: "products",
optionLabel: "Select order...",
dataTextField: "Order.ShipCity",
dataValueField: "OrderID",
dataSource: {
type: "odata",
serverFiltering: true,
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Order_Details?$expand=Order"
}
}
}).data("kendoDropDownList");
// Bind "click" event on button "Filter"
$("#filter").on("click", function () {
var mindate = $('#datetimepicker1').data("kendoDatePicker").value();
var maxdate = $('#datetimepicker2').data("kendoDatePicker").value();
var product = $("#products").data("kendoDropDownList").value();
var order = $("#orders").data("kendoDropDownList").value();
if (!mindate || !maxdate || !product || !order) {
var content = "";
if (!mindate)
content += "<div class=\"k-error-colored\">mindate is not defined!</div>";
if (!maxdate)
content += "<div class=\"k-error-colored\">maxdate is not defined!</div>";
if (!product)
content += "<div class=\"k-error-colored\">product is not defined!</div>";
if (!order)
content += "<div class=\"k-error-colored\">order is not defined!</div>";
$("#filter-msg").data("kendoWindow")
.content(content)
.center()
.open();
return false;
}
var condition = {
logic: "and",
filters: [{
field: "OrderDate",
operator: "ge",
value: mindate
}, {
field: "OrderDate",
operator: "le",
value: maxdate
}]
};
grid.dataSource.filter(condition);
});
var grid = $("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: {
type: "number"
},
Freight: {
type: "number"
},
ShipName: {
type: "string"
},
OrderDate: {
type: "date"
},
ShipCity: {
type: "string"
}
}
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
filterable: true,
sortable: true,
pageable: true,
columns: [{
field: "OrderID",
filterable: false
},
"Freight", {
field: "OrderDate",
title: "Order Date",
width: 100,
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name",
width: 200
}, {
field: "ShipCity",
title: "Ship City"
}]
}).data("kendoGrid");
Here is the js fiddle: http://jsfiddle.net/XHW3w/1/

Done, you can check using length property of dataSource.data
Here is the updated jsfiddle
grid.dataSource.filter(condition);
console.log(grid.dataSource.data.length);
if(grid.dataSource.data.length <= 1)
$("#filter-msg").data("kendoWindow")
.content("<div class=\"k-error-colored\">No record found!</div>")
.center()
.open();

Related

KendoUI populate dropdown

I am new to kendoUI and I need some assistance with getting the data that is returned from a function to populate into the dropdown. I am currently getting [object HTMLSelectElement] - you can see in the image attached. Any help is appreciated.
data is returned in function
dropdown is not showing the years returned
LoadAcceptedSubmissionsGrid: function (module) {
// Grid for "Accepted" tab
var isAccepted = "true";
gridAcceptedSubmissions = $("#gridAcceptedSubmissions").kendoGrid({
dataSource: {
type: "json",
serverPaging: true,
serverSorting: true,
serverFiltering: true,
allowUnsort: true,
transport: {
read: function (options) {
var strFilter = JSON.stringify(options.data.filter);
var strSort = JSON.stringify(options.data.sort);
var pageSize = options.data.pageSize === undefined && gridAcceptedSubmissions !== null ?
gridAcceptedSubmissions.dataSource.total() :
options.data.pageSize;
var acceptedSubmissionsUrl = commonUrl + "/Forms/Submissions/"
+ upacsSessionId + "/" + userId + "/" + form + "/" + isAccepted + "/"
+ options.data.page + "/" + pageSize + "/" + options.data.skip;
$.ajax({
type: "POST",
url: acceptedSubmissionsUrl,
xhrFields: {
withCredentials: true
},
data: {
filter: strFilter,
sort: strSort
},
success: function (response) {
options.success(response);
},
error: function (result) {
options.error(result);
}
});
}
},
pageSize: 10,
batch: false,
schema: {
total: function (response) {
return response.total;
},
data: function (response) {
return response.values;
},
model: {
id: "submissionId",
fields: {
state: { editable: false, type: "string", sort: "asc" },
fipsCode: { editable: false, type: "number", sort: "asc" },
year: { editable: false, type: "number", sort: "desc" },
name: { editable: false, type: "string" },
createdBy: { editable: false, type: "string" },
createdOn: { editable: false, type: "date" },
lastModifiedBy: { editable: false, type: "string" },
lastModifiedOn: { editable: false, type: "date" },
isEditable: { editable: false, type: "boolean" },
isReviewable: { editable: false, type: "boolean" }
}
}
}
},
groupable: false,
sortable: {
showIndexes: true,
mode: "multiple"
},
resizable: true,
selectable: "row",
scrollable: true,
filterable: true,
navigatable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 10
},
dataBound: this.GridDataBound,
columns: [
{
field: "submissionId",
title: "Id",
},
{
field: "state",
title: "State",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("state", "name", true)
},
sort: "ascending"
},
{
field: "year",
title: "Year",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("year", null, true)
},
sort: "descending"
},
{
field: "status",
title: "Status",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("status", null, true)
}
},
{
field: "createdBy",
title: "Initiated By",
filterable: {
ui: this.FormCreatedByAcceptedFilter
}
},
{
field: "createdOn",
title: "Initiated On",
format: "{0:g}",
},
{
field: "lastModifiedBy",
title: "Modified By",
filterable: {
ui: this.FormLastModifiedByAcceptedFilter
}
},
{
field: "lastModifiedOn",
title: "Modified On",
format: "{0:g}"
},
{
title: "Action",
headerTemplate: "<div class='headerTemplate'><span class='headerText'>Action</span>" +
"<button class='clearAllFilters' id='clearAllFiltersAcceptedSubmissions' tabindex=0> Clear All Filters</button></div>",
command: [
{
name: "View",
text: " ",
visible: function (dataItem) { return !dataItem.isEditable },
template: function () {
var tmpl = "<a role='button' class='k-button k-button-icontext k-grid-View' title='View Form' tabindex=0>" +
"<i aria-hidden='true' class='fa fas fa-eye'><span class='sr-only'>View form</span></i></a>";
return tmpl;
},
click: function (e) {
e.preventDefault();
var data = this.dataItem($(e.target).closest("tr"));
$("#submissionId").val(data.submissionId);
commonFormsModule.UpdateFormMetadata(data, "from-grid")
gridSubmissionStatusHistory.dataSource.read();
commonFormsModule.SwitchTo("view-existing-form", module);
}
},
{
name: "View History",
text: " ",
visible: function (dataItem) { return !dataItem.isReviewable },
template: function () {
var tmpl = "<a role='button' class='k-button k-button-icontext k-grid-ViewHistory' title='View Form History' tabindex=0>" +
"<i aria-hidden='true' class='fa fas fa-history'><span class='sr-only'>View form history</span></i></a> ";
return tmpl;
},
click: function (e) {
var data = this.dataItem($(e.target).closest("tr"));
$("#submissionId").val(data.submissionId);
commonFormsModule.UpdateFormMetadata(data, "from-grid")
gridSubmissionStatusHistory.dataSource.read();
commonFormsModule.SwitchTo("view-status-history", module);
}
}
],
},
]
}).data("kendoGrid");
gridAcceptedSubmissions.hideColumn(0);
$("#clearAllFiltersAcceptedSubmissions").click(function () {
gridAcceptedSubmissions.dataSource.filter({});
});
},
Without seeing what BuildMultiCheckboxDataSource is doing, I can only make assumptions.
However, since you have declared year as an IEnumerable<int> then the datasource does not need to be anything elaborate. Simply set it to the collection being returned by the server:
{
field: "year",
title: "Year",
filterable: {
multi: true,
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/my-endpoint-to-fetch-years-here"
}
}
})
},
sort: "descending"
}

filter a datasource using a multiselect Kendo

I have a grid and a multiselect ,i want to filter the grid by the multiselect according to what i select ,and when i de select,the grid should be filterd accordingly,here is my grid:
$("#grid").kendoGrid({
dataSource: ds2,
height: 550,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [
{ field: "name",
title: "Name",width:"50px"},
{ field: "Description",
title: "Description", width: "80px"
},
{ field: "WindSpeed",
title: "Wind Speed", width: "40px"
},
{ field: "RPM",
title: "RPM", width: "40px"
},
{ field: "Power",
title: "Power", width: "40px"
}
]
});
the data which bind the datasource:
var ds1 = new kendo.data.DataSource({
data: rsturn_f.EventNames
});
var ds2 = new kendo.data.DataSource({
data: rsturn_f.Data
});
and here is the multi select:
$("#evnts").kendoMultiSelect({
placeholder: "Select products...",
dataTextField: "Nme",
dataValueField: "Nme",
//autoBind: false,
select: onSelect,
deselect: onDeselect,
dataSource: ds1
});
by onselect i do this:
function onSelect(e) {
ds2.filter({ field: "Description", operator: "startswith", value: e.dataItem });
}
now if i want to filter on multiple value and un filter by removing the values from multiselect i dont know what should i do,any idea?
You have to use change event of the Multiselect. You can directly use a function in the operation attribute which is passed to the dataSource filter API.
function onChange(e) {
ds2.filter({ field: "Description", value: this.value(),
operator: function(currentValue, filterValues){
if(filterValues.length===0){
return true;
}
if(filterValues.indexOf(currentValue)!==-1){
return true;
}
return false;
}
});
}

KendoUI Grid Filter Posts Twice

I have this grid with a custom multi-select filter. When I click the filter icon an AJAX method calls an API to grab filter values. The method call is defined in the DocType column.
Here is my grid builder function:
$("#attachmentsGrid").kendoGrid({
pageable: {
change: function() {
CH.RelatedItems.GridPager();
}
},
scrollable: false,
sortable: true,
dataSource: attachments,
filterable: {
extra: false,
operators: {
string: {
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to",
contains: "Contains",
}
}
},
columns:
[
{
title: "id",
field: "Id", //turns out this needs to be lower case
sortable: false,
filterable: false,
template: "<input name='cbCheckboxColumn' type='checkbox' onclick='CH.RelatedItems.ToggleAttachmentsByCheckboxColumn()' data-row='#: Id#' />",
headerTemplate: "<input id='cbCheckboxHeader' type='checkbox' onclick='CH.RelatedItems.ToggleAttachmentsByCheckboxHeader()'",
width: "18px",
},
{
title: "Exists?",
field: "IsAlreadyAttached",
type: "boolean",
sortable: false,
template: "<div style='text-align: center'>#: IsAlreadyAttached #</div>",
filterable: false,
width: "110px",
},
{
title: "Icon",
field: "DocType",
sortable: true,
template: "<div style='text-align: center'><img src='" + config.SPHostUrl + "/_layouts/images/#: DocIcon #' /></div>",
width: "60px",
filterable: {
ui: CH.RelatedItems.AttachmentsIconFilter,
extra: false,
},
},
{
title: "File Name",
field: "Name",
sortable: true,
filterable: false,
template: "<a href='#: Url#' target='_blank'>#: Name#</a>",
width: "650px",
},
{
title: "Modified",
field: "LastModifiedDateOnly",
template: "<span>#: LastModified#</span>",
sortable: true,
width: "250px",
filterable: {
ui: CH.RelatedItems.AttachmentsDateFilter,
extra: false
}
},
],
dataBound: CH.RelatedItems.PostGridDataBound
});
The AttachmentsIconFilter function is here:
pub.AttachmentsIconFilter = function (element) {
var menu = $(element).parent();
menu.find(".k-filter-help-text").text("Show document types:");
menu.find("[data-role=dropdownlist]").remove();
var multiSelect = element.kendoMultiSelect({
dataSource: {
transport: {
read: {
datatype: "jsonp",
url: config.WorkPaperViewRelativePath + "/_RelatedItemsPopup/GetAttachmentsUniqueDocIcons/" + config.SPQueryString
}
}
},
}).data("kendoMultiSelect");
menu.find("[type=submit]").on("click", { widget: multiSelect }, CH.RelatedItems.AttachmentsFilterByIcon);
}
When the AttachmentsIconFilter runs, the AJAX call get made twice:
Kendo Double GET
I thought that the property: filter: { extra: false } was supposed to prevent this double GET?
Also, when I select my filters and the grid make a new request to get the filtered records, it does a double POST. The function for the call to filter the grid is here:
pub.AttachmentsFilterByIcon = function (e) {
var icons = e.data.widget.value();
var filter = { logic: "or", filters: [] };
for (var i = 0; i < icons.length; i++)
{
filter.filters.push({ field: "DocIcon", operator: "Contains", value: icons[i].Contains });
}
$("#attachmentsGrid").data("kendoGrid").dataSource.filter(filter);
}
Any help here? What am I missing?

kendo grid server re filtering the data source

$(document).ready(function () {
var agenciesData = new kendo.DataToken.DataSource({
type: 'webapi',
transport: {
read: { url: "/api/Agencies/", dataType: "json", data: { activity: getActivity() } },
create: { url: "/api/Agencies", type: "POST", dataType: "json" },
destroy: { url: "/api/Agencies/{0}", type: "DELETE" },
update: { url: "/api/Agencies/{0}", type: "PUT" },
idField: "ID"
},
filter: [{ field: "Activity", operator: "eq", value: getActivity() }],
pageSize: 15,
page: 1,
total: 0,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
schema: {
data: "Data",
total: "Total",
model: {
id: "ID",
fields: {
ID: { editable: false, type: "number" },
AgencyName: { type: "string" },
AgentName: { type: "string" },
Address: { type: "string" },
City: { type: "string" },
Tel1: { type: "string" },
Tel2: { type: "string" },
Pele: { type: "string" },
Activity: { type: "number" },
ToDate: { type: "date" }
}
}
}
});
$("#agenciesGrid").kendoGrid({
dataSource: agenciesData,
toolbar: [{ text: "valid", className: "validAgents" }, { text: "not valid", className: "notValid" }, { text: "all", className: "allAgents" }, { text: "potential", className: "potetial" }],
editable: false,
navigatable: true,
sortable: true,
autoBind: false,
height: 430,
pageable: { refresh: true },
columns: [
{ field: "ID", hidden: true },
{ field: "AgencyName", title: "agency", width: 150, filterable: { cell: { operator: "contains" } } },
{ field: "AgentName", title: "agent", width: 150, filterable: { cell: { operator: "contains" } } },
{ field: "Address", title: "address", width: 200, template: "#= Address + ' ' + City #", filterable: false },
{ field: "Tel1", title: "phones", width: 300, template: "#= Tel1 + ' : ' + Tel2 + ' : ' + Pele #", filterable: false },
{ field: "Activity", title: "active", width: "90px" },
{ field: "ToDate", title: "end Contract", type: "date", width: 90, format: "{0:dd/MM/yyyy}", parseFormats: ["yyyy-MM-ddThh:mm:ss"] }
]
});
$(".validAgents").click(function () { //valid
$("#myActivity").val("1");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "1" });
});
$(".notValid").click(function () {//notValid
$("#myActivity").val("2");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "2" });
});
$(".potetial").click(function () {//potetial
$("#myActivity").val("3");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "3" });
});
});
function getActivity(){
var myActivity = $("#myActivity").val();
return myActivity;
}
When I use kendo grid already filtered by parameter like : $('#someGrid').data().kendoGrid.dataSource.read({ activity: value });
i see the get: https://localhost:44305/api/Agencies/?sort=&page=1&pageSize=15&group=&filter=&activity=1
The grid is filter as expected but, when I want to do paging, sorting, refresh - I get the whole data ignoring the filter that i made.
and I see the get: https://localhost:44305/api/Agencies/?sort=&page=1&pageSize=15&group=&filter=
How can I save my filter state to do paging and sorting on the data came from the server side ?
even when i used differen approach like "scrollable: { virtual: true }" and when i scroll down - every request is without the filtering...
Thanks
Did you try
var agenciesData = new kendo.DataToken.DataSource({
filter : function () {
return object;
}
});
I mean try using filter as a function and you can do your logic inside the function depending on the situation.

After I click on the Update button in Kendo Grid, the insert into the database works but this doesnt cause the grid to exit edit mode

Below is my grid.
If you look at the save: event, you'll notice an AJAX call.
This AJAX call IS firing, data IS being inserted into the database and I can even see the alert function going through. However, the grid does not exit edit mode for the row I'm inline editing. I'm not sure what's going on because the error message is terrible. I keep getting:
TypeError: Cannot read property 'data' of undefined [http://localhost/x/Scripts/kendo.web.min.js:13]
Here's the grid:
function directorsOrRecipients(e)
{
awardTitleId = e.data.AwardTitleId;
var detailRow = e.detailRow;
detailRow.find(".childTabstrip").kendoTabStrip({
animation: {
open: { effects: "fadeIn" }
}
});
detailRow.find(".directorsOrRecipients").kendoGrid({
reorderable: true,
resizable: true,
dataSource: {
transport: {
read: {
url: "http://localhost/x/api/Awards/directors/" + awardTitleId,
type: "GET"
},
},
schema: {
model: {
id: "AwardDirectorId",
fields: {
"AwardDirectorId": { editable: false, type: "number" },
"namefirstlast": { editable: true, type: "string" },
"directorsequence": { editable: true, type: "number", validation: { min: 1 } },
"isonballot": { editable: true, type: "string" },
"concatenation": { editable: true, type: "string" },
"MoreNames": { editable: true, type: "number", validation: { min: 0 } },
}
}
}
},
columns: [
{ field: "AwardDirectorId", title: "Award Director Id" },
{ field: "namefirstlast", title: "Name", editor: namesAutoComplete },
{ field: "directorsequence", title: "Director Sequence", format: "{0:n0}" },
{ field: "isonballot", title: "On ballot?", editor: onBallotDropDownEditor },
{ field: "concatenation", title: "Concatenation" },
{ field: "MoreNames", title: "More names?", format: "{0:n0}" },
{ command: ["edit"], title: " ", width: 100 }],
sortable: true,
sort: { field: "namefirstlast", dir: "desc" },
editable: "inline",
toolbar: [{ name: "create", text: "Add New Director/Recipient" }],
save: function(e)
{
debugger;
if (e.data != "undefined")
{
$.ajax({
url: "http://localhost/x/api/awards/directors",
type: "POST",
dataType: "json",
data: $.parseJSON(directorData)
}).done(function()
{
alert('done!');
});
}
}
});
function onBallotDropDownEditor(container, options)
{
var data = [
{ "onBallotId": 1, "onBallotDescription": "Yes" },
{ "onBallotId": 2, "onBallotDescription": "No" }];
$('<input required data-text-field="onBallotDescription" data-value-field="onBallotDescription" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: data
});
}
}
After Success in Ajax call try this,
$('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();
In controller update function return an object insted of empty Json, like this it worked for me
return Json(ModelState.IsValid ? new object() : ModelState.ToDataSourceResult());

Resources