How to add background color to a KendoUI Grid - kendo-ui

I have a KendoUI Grid that is working just fine but I cannot add background color to rows.
I found some code that is supposed to iterate over the rows, but when I run it it simply goes in an infinite loop.
There are many posts about this topic but most of them are far more complex than I would like.
Any help would be greatly appreciated.
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
type: "jsonp",
transport: {
read: "XXXX.xpRest.xsp/xpRest1"},
pageSize: 20},
batch: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
pageSize: 15,
height: 543,
selectable : true,
columns : [{
field : "name",
title : "Name"
},{
field : "strDate",
title : "Start Date",
width : 150
},{
field : "$10",
title : "End Date Date",
width : 150
}],
dataBound: function () {
dataView = this.dataSource.view();
//<!-- for (var i = 0; i < dataView.length; i++) {-->
//<!-- if (i = 0) {-->
//<!-- var uid = dataView[i].uid;-->
//<!-- $("#grid tbody").find("tr[data-uid=" + uid + "]").addClass("onCall"); //alarm's in my style and we call uid for each row-->
//<!-- }-->
//<!-- }-->
}
});
});

dataBound: function (e) {
// Color rows
var rows = e.sender.tbody.children();
for (var j = 0; j < rows.length; j++) {
var row = $(rows[j]);
row.css('background-color', '#FFFFE0');
}
}

Related

Kendo Grid : Blank space in the end when you resize(reduce) any column

I have a grid and when i resize (reduce) any column, there is a white space shows up in the end of the grid. I have checked with the Kendo official samples and it seems like in some samples the shown behavior is in their samples.
I tried setting up width for header, cell content etc.. but its still shows some UI issues and i have multiple grids and i need a generic fix.
If its not an issue and a behavior then somebody please have a look at this and explain how to fix it.
I have added a normal screen shot and resized screenshot.
normal
after resize
For testing it out, i have added a jsfiddle.,
http://jsfiddle.net/49bhz2sk/
html
<div class="panel panel-body">
<div id="fleetInfoGridDisplayDummy" class="" data-bind="autoHeightContainer:true"></div>
</div>
script
$("#fleetInfoGridDisplayDummy").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
},
pageSize: 20
},
navigatable: true,
selectable: true,
sortable: true,
reorderable: true,
resizable: true,
scrollable: { virtual: true },
columnMenu: true, // Needed to hide and show columns.
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [{
template: "<div class='customer-photo'" +
"style='background-image: url(../content/web/Customers/#:data.CustomerID#.jpg);'></div>" +
"<div class='customer-name'>#: ContactName #</div>",
field: "ContactName",
title: "Contact Name",
width: 240
}, {
field: "ContactTitle",
title: "Contact Title"
}, {
field: "CompanyName",
title: "Company Name"
}, {
field: "Country",
width: 150
}]
});
I have posted this in telerik forum and got a reply from the admin, here is how they suggested to resolve the issue. Posted here so that someone else can benefit from this.
Answer proposed by 'Drew B.' also works, i have seen that too in another post. The the code i posted is less cumbersome with minimal coding.
columnResize: function (e) {
// what is thead and tbody: https://docs.telerik.com/kendo-ui/api/javascript/ui/grid#fields
var grid = e.sender,
gridHeaderTable = grid.thead.parent(),
gridBodyTable = grid.tbody.parent();
// what is wrapper: https://docs.telerik.com/kendo-ui/api/javascript/ui/widget/fields/wrapper
// what is scrollbar(): https://docs.telerik.com/kendo-ui/api/javascript/kendo/fields/support
if (gridBodyTable.width() < grid.wrapper.width() - kendo.support.scrollbar()) {
// remove the width style from the last VISIBLE column's col element
gridHeaderTable.find("> colgroup > col").last().width("");
gridBodyTable.find("> colgroup > col").last().width("");
// remove the width property from the last VISIBLE column's object
// https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/fields/columns
grid.columns[grid.columns.length - 1].width = "";
// remove the Grid tables' pixel width
gridHeaderTable.width("");
gridBodyTable.width("");
}
},
According to various kendo sources, this is a mixture of observed normal behavior (2013), and unexpected behavior (2017). Kendo does provide a workaround for this issue, as I suspect it isn't necessarily kendo related but more an HTML/Table feature.
<style>
.k-grid {
width: 700px;
}
</style>
<div id="grid1"></div>
<script>
function getMasterColumnsWidth(tbl) {
var result = 0;
tbl.children("colgroup").find("col").not(":last").each(function (idx, element) {
result += parseInt($(element).outerWidth() || 0, 10);
});
return result;
}
function adjustLastColumn() {
var grid = $("#grid1").data("kendoGrid");
var contentDiv = grid.wrapper.children(".k-grid-content");
var masterHeaderTable = grid.thead.parent();
var masterBodyTable = contentDiv.children("table");
var gridDivWidth = contentDiv.width() - kendo.support.scrollbar();
masterHeaderTable.width("");
masterBodyTable.width("");
var headerWidth = getMasterColumnsWidth(masterHeaderTable),
lastHeaderColElement = grid.thead.parent().find("col").last(),
lastDataColElement = grid.tbody.parent().children("colgroup").find("col").last(),
delta = parseInt(gridDivWidth, 10) - parseInt(headerWidth, 10);
if (delta > 0) {
delta = Math.abs(delta);
lastHeaderColElement.width(delta);
lastDataColElement.width(delta);
} else {
lastHeaderColElement.width(0);
lastDataColElement.width(0);
}
contentDiv.scrollLeft(contentDiv.scrollLeft() - 1);
contentDiv.scrollLeft(contentDiv.scrollLeft() + 1);
}
$("#grid1").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Employees"
},
pageSize: 6,
serverPaging: true,
serverSorting: true
},
height: 430,
pageable: true,
resizable: true,
columnResize: adjustLastColumn,
dataBound: adjustLastColumn,
columns: [{
field: "FirstName",
title: "First Name",
width: "100px"
}, {
field: "LastName",
title: "Last Name",
width: "150px"
}, {
field: "Country",
width: "100px"
}, {
field: "City",
width: "100px"
}, {
field: "Title",
width: "200px"
}, {
template: " "
}]
});
</script>

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

Fetching kendo grid row data on selecting checkbox

I am trying to fetch kendo data on selecting particular row using checkbox.
This is part of code of controller.js
$scope.campaignLabelOptions = {
dataSource: {
data: [] ,
},
sortable: true,
pageable : {pageSizes : [5, 10, 25, 50]},
filterable : true,
resizable :true,
reordable :true,
scrollable:true,
columnMenu: true,
selectable :true,
editable: {
confirmation: "Are you sure that you want to delete this record?",
mode: "popup"
},
columns : [
{template: "<input type='checkbox' class='checkbox' ng-click='onClick($event)'/>" },
{field : "campaign_name", title :"Campaign Name", width : "150px", attributes: {style: "font-size: 12px"}},
// {field : "time_line", title :"Timeline", width : "100px",attributes: {style: "font-size: 12px"} },
{field : "spend", title :"Spend", width : "90px",attributes: {style: "font-size: 12px"} },
{field : "campaign_group_status", title :"Status", width : "85px", attributes: {style: "font-size: 12px"}},
{field : "performance", title :"Performance", width : "130px", attributes: {style: "font-size: 12px"}},
// {field : "creation_time", title :"Created Time", width : "135px", attributes: {style: "font-size: 12px"}},
],
};
$scope.checkedIds = [];
$scope.showCheckboxes = function(){
var checked = [];
for(var i in $scope.checkedIds){
if($scope.checkedIds[i]){
checked.push(i);
}
}
alert(checked);
};
$scope.onClick = function(e){
console.log(e);
var element =$(e.currentTarget);
var checked = element.is(':checked');
var row = element.closest("tr");
var grid = element.closest('kendoGrid').getKendoGrid();
var dataItem = grid.dataItem(row);
$scope.checkedIds[dataItem.EmployeeID] = checked;
if (checked) {
row.addClass("k-state-selected");
} else {
row.removeClass("k-state-selected");
}
};
I have copied similar code from http://dojo.telerik.com/exAB/5 for select logic . But here grid variable is coming undefined. Its not getting getKendoGrid() method..
Is there any better way to get row data? If yes what and if not -- how to use this current code?

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 toolbar buttons

I am using a Kendo UI grid, which looks like this:
function refreshGrid()
{
$(".k-pager-refresh.k-link").click();
}
var editWindow;
var fields= {FullName: {type: "string"}, Email: {type: "string"}, LogCreateDate: {type: "date"}};
var gridColumns =
[{
width: 90,
command: {
name: "edit",
text: "Edit",
click: function(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
editWindow = $("#edit").kendoWindow({
title: "Edit User",
modal: true,
visible: false,
resizable: false,
width: 800,
height: 400,
content: 'myediturl' + dataItem.ID
});
editWindow.data("kendoWindow").center().open();
return false;
}
}
},
{
width: 90,
command: {
name: "delete",
text: "Delete",
click: function(e) {
//alert(this.dataItem($(e.currentTarget).closest("tr")).ID);
var id = this.dataItem($(e.currentTarget).closest("tr")).ID;
if (confirm("Are you sure you want to delete this user?"))
{
$.ajax({
type: 'POST',
url: '#Url.Action("deleteuser","admin",null, "http")' + "/" + this.dataItem($(e.currentTarget).closest("tr")).ID,
success: function (param) { refreshGrid(); },
async: false
});
}
return false;
}
}
},
{
field: "FullName",
title: "Full Name",
type: "string"
},
{
field: "Email",
title: "Email",
type: "string"
},
{
field: "LogCreateDate",
title: "Created",
type: "date",
template: '#= kendo.toString(LogCreateDate,"MM/dd/yyyy") #'
}];
//getSorts the columns of the grid
function getColumns() {
//Parsing the set of columns into a more digestable form
var columns = "";
for (var col in gridColumns) {
if (!!gridColumns[col].field)
{
if (columns.length > 0) {
columns += ";";
}
columns += gridColumns[col].field + "," + gridColumns[col].type;
}
}
return columns;
}
function getSorts(sortObject) {
if (!(sortObject)) {
return "";
}
//Getting the row sort object
var arr = sortObject;
if ((arr) && (arr.length == 0)) {
return "";
}
//Parsing the sort object into a more digestable form
var columnSet = getColumns();
var returnValue = "";
for (var index in arr) {
var type = "";
for (var col in gridColumns) {
if (gridColumns[col].field === arr[index].field) {
type = gridColumns[col].type;
}
}
returnValue += ((returnValue.length > 0) ? (";") : ("")) + arr[index].field + "," + (arr[index].dir === "asc") + "," + type;
}
return returnValue;
}
var grid;
$(function () {
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "mydatasourceurl",
type: "POST",
},
parameterMap: function (data, type) {
data.filters = JSON.stringify(data.filter);
data.columns = JSON.stringify(getColumns());
data.sorts = JSON.stringify(getSorts(data.sort));
console.log(data);
return data;
}
},
schema: {
fields: fields,
data: "Data",
total: "Total"
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
toolbar: [{
name: "Add",
text: "Add new record",
click: function(e){console.log("foo"); return false;}
}],
height: 392,
groupable: false,
sortable: true,
filterable: true,
pageable: {
refresh: true,
pageSizes: true
},
columns: gridColumns
});
grid = $("#grid").data("kendoGrid");
});
My create toolbar action is not triggered on click. How can I resolve this problem, is Kendo UI able to handle toolbar click events? The best solution I came up with looks like this:
$(".k-button.k-button-icontext.k-grid-add").click(function () {
//If the window doesn't exist yet, we create and initialize it
if (!grids[gridContainerID].addWindow.data("kendoWindow")) {
grids[gridContainerID].addWindow.kendoWindow({
title: "Add " + entityName,
width: "60%",
height: "60%",
close: onClose,
open: onAddOpen,
content: addUrl
});
}
//Otherwise we just open it
else {
grids[gridContainerID].addWindow.data("kendoWindow").open();
}
//Centralizing and refreshing to prepare the layout
grids[gridContainerID].addWindow.data("kendoWindow").center();
grids[gridContainerID].addWindow.data("kendoWindow").refresh();
return false;
});
Thanks in advance.
Instead of using that complex selector use the one that Kendo UI creates from name:
toolbar: [
{
name: "Add",
text: "Add new record",
click: function(e){console.log("foo"); return false;}
}
],
and then:
$(".k-grid-Add", "#grid").bind("click", function (ev) {
// your code
alert("Hello");
});
In kendogrid docs here shows that there is no click configuration for grid toolbar buttons like grid.colums.commands.
To solve this problem you can reference following steps:
create a template for toolbar
<script id="grid_toolbar" type="text/x-kendo-template">
<button class="k-button" id="grid_toolbar_queryBtn">Query</button>
</script>
apply tempate to toolbar
toolbar:[{text:"",template: kendo.template($("#grid_toolbar").html())}]
add event listener to button
$("#grid_toolbar_queryBtn").click(function(e) {
console.log("[DEBUG MESSAGE] ", "query button clicked!");
});

Resources