Related
Executable code snippet: https://demos.telerik.com/kendo-ui/grid/index (Just go to this example and hit "Edit")
I want to display the full list of parent groups displayed as a list in the groupFooterTemplate of the child group.
{
field: "Discontinued",
title: "In Stock",
template: "<span id='badge_#=ProductID#' class='badgeTemplate'></span>",
groupFooterTemplate: (data) => { return this.getPathToDataItem(data)} ,
width: 130,
}
Above I change one of the columns to reference a function getPathToDataItem(data) in its groupFooterTemplate. Now I define the function:
private getPathToDataItem(data): string {
var path: string = '';
//Javascript - JQuery - Black magic goes here!
return path; //Should look something like Seafood/Unavailable (assuming my groups are Category,
InStock in that order!)
}
to actually get the template. I want to use javascript/jquery/kendo to get the full list of groups in play and create a path for them. So if the groups in play are Category, Instock then the template should display Seafood/Unavailable, Produce/Available, etc.
My issue is I can't figure out how to get the parent groups in the child group template! The last one is easy, as that's just data.value, but how do I get the prior groups? I suspect I will need to do something like:
group1/group2/.../data.value
but how do I get group1, group2, and in general, groupN?
Any help would be appreciated, thanks!
Ok. Stick the code below in the Telerik DOJO. By the way, remove the typescript tag from your question. This isn't typescript, this is Kendo UI jQuery. If the groups in play are Category and In Stock, the footer will show something like 'Seafood/available', 'Seafood/not available', etc. The idea to get the prior groups is to assign a reference to the Kendo grid object so that we can access the dataSource in the groupFooterTemplate function and that's where the Javascript black magic happens. Hope the code below will help you solve your problem.
<!DOCTYPE html>
<html>
<head>
<base href="https://demos.telerik.com/kendo-ui/grid/index">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2021.2.511/styles/kendo.bootstrap-v4.min.css" />
<script src="https://kendo.cdn.telerik.com/2021.2.511/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2021.2.511/js/kendo.all.min.js"></script>
</head>
<body>
<script src="//cdnjs.cloudflare.com/ajax/libs/jszip/2.4.0/jszip.min.js"></script>
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/detailproducts",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/detailproducts/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/detailproducts/Destroy",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
autoSync: true,
aggregate: [{
field: "TotalSales",
aggregate: "sum"
}],
group: {
field: "Category.CategoryName",
dir: "desc",
aggregates: [
{ field: "TotalSales", aggregate: "sum" }
]
},
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
Discontinued: { type: "boolean", editable: false },
TotalSales: { type: "number", editable: false },
TargetSales: { type: "number", editable: false },
LastSupply: { type: "date" },
UnitPrice: { type: "number" },
UnitsInStock: { type: "number" },
Category: {
defaultValue: {
CategoryID: 8,
CategoryName: "Seafood"
}
},
Country: {
defaultValue: {
CountryNameLong: "Bulgaria",
CountryNameShort: "bg"
}
}
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
columnMenu: {
filterable: false
},
height: 680,
editable: "incell",
pageable: true,
sortable: true,
navigatable: true,
resizable: true,
reorderable: true,
groupable: true,
filterable: true,
dataBound: onDataBound,
toolbar: ["excel", "pdf", "search"],
columns: [{
selectable: true,
width: 75,
attributes: {
"class": "checkbox-align",
},
headerAttributes: {
"class": "checkbox-align",
}
}, {
field: "ProductName",
title: "Product Name",
template: "<div class='product-photo' style='background-image: url(../content/web/foods/#:data.ProductID#.jpg);'></div><div class='product-name'>#: ProductName #</div>",
width: 300,
groupFooterTemplate: function(dataItem) {
var ds = grid.dataSource;
var groupingFields = [];
for (let a = 0; a < ds._group.length; a++) {
groupingFields.push(ds._group[a].field);
}
var items = dataItem.items;
for (let a = 0; a < items.length; a++) {
if (items[a].hasOwnProperty('hasSubgroups')) {
items = items[a].items;
break;
}
}
var path = '';
for (let a = 0; a < items.length; a++) {
var item = items[a];
for (let b = 0; b < groupingFields.length; b++) {
var groupingField = groupingFields[b];
if (b > 0) {
path += '/';
}
if (groupingField.includes('.')) {
path += groupingField.split('.').reduce(getValue, item);
} else {
if (groupingField === 'Discontinued') {
path += item[groupingField] ? 'available' : 'not available';
} else {
path += item[groupingField];
}
}
if (groupingField === dataItem.field) {
break;
}
}
break;
}
return path;
function getValue(obj, prop) {
return obj[prop];
}
},
}, {
field: "UnitPrice",
title: "Price",
format: "{0:c}",
width: 105
}, {
field: "Discontinued",
title: "In Stock",
template: "<span id='badge_#=ProductID#' class='badgeTemplate'></span>",
width: 130,
}, {
field: "Category.CategoryName",
title: "Category",
editor: clientCategoryEditor,
groupHeaderTemplate: "Category: #=data.value#, Total Sales: #=kendo.format('{0:c}', aggregates.TotalSales.sum)#",
width: 125
}, {
field: "CustomerRating",
title: "Rating",
template: "<input id='rating_#=ProductID#' data-bind='value: CustomerRating' class='rating'/>",
editable: returnFalse,
width: 140
}, {
field: "Country.CountryNameLong",
title: "Country",
template: "<div class='k-text-center'><img src='../content/web/country-flags/#:data.Country.CountryNameShort#.png' alt='#: data.Country.CountryNameLong#' title='#: data.Country.CountryNameLong#' width='30' /></div>",
editor: clientCountryEditor,
width: 120
}, {
field: "UnitsInStock",
title: "Units",
width: 105
}, {
field: "TotalSales",
title: "Total Sales",
format: "{0:c}",
width: 140,
aggregates: ["sum"],
}, {
field: "TargetSales",
title: "Target Sales",
format: "{0:c}",
template: "<span id='chart_#= ProductID#' class='sparkline-chart'></span>",
width: 220
},
{ command: "destroy", title: " ", width: 120 }],
}).data('kendoGrid');
});
function onDataBound(e) {
var grid = this;
grid.table.find("tr").each(function () {
var dataItem = grid.dataItem(this);
if (dataItem === undefined) {
return;
}
var themeColor = dataItem.Discontinued ? 'success' : 'error';
var text = dataItem.Discontinued ? 'available' : 'not available';
$(this).find(".badgeTemplate").kendoBadge({
themeColor: themeColor,
text: text,
});
$(this).find(".rating").kendoRating({
min: 1,
max: 5,
label: false,
selection: "continuous"
});
$(this).find(".sparkline-chart").kendoSparkline({
legend: {
visible: false
},
data: [dataItem.TargetSales],
type: "bar",
chartArea: {
margin: 0,
width: 180,
background: "transparent"
},
seriesDefaults: {
labels: {
visible: true,
format: '{0}%',
background: 'none'
}
},
categoryAxis: {
majorGridLines: {
visible: false
},
majorTicks: {
visible: false
}
},
valueAxis: {
type: "numeric",
min: 0,
max: 130,
visible: false,
labels: {
visible: false
},
minorTicks: { visible: false },
majorGridLines: { visible: false }
},
tooltip: {
visible: false
}
});
kendo.bind($(this), dataItem);
});
}
function returnFalse() {
return false;
}
function clientCategoryEditor(container, options) {
$('<input required name="Category">')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataTextField: "CategoryName",
dataValueField: "CategoryID",
dataSource: {
data: categories
}
});
}
function clientCountryEditor(container, options) {
$('<input required name="Country">')
.appendTo(container)
.kendoDropDownList({
dataTextField: "CountryNameLong",
dataValueField: "CountryNameShort",
template: "<div class='dropdown-country-wrap'><img src='../content/web/country-flags/#:CountryNameShort#.png' alt='#: CountryNameLong#' title='#: CountryNameLong#' width='30' /><span>#:CountryNameLong #</span></div>",
dataSource: {
transport: {
read: {
url: " https://demos.telerik.com/kendo-ui/service/countries",
dataType: "jsonp"
}
}
},
autoWidth: true
});
}
var categories = [{
"CategoryID": 1,
"CategoryName": "Beverages"
}, {
"CategoryID": 2,
"CategoryName": "Condiments"
}, {
"CategoryID": 3,
"CategoryName": "Confections"
}, {
"CategoryID": 4,
"CategoryName": "Dairy Products"
}, {
"CategoryID": 5,
"CategoryName": "Grains/Cereals"
}, {
"CategoryID": 6,
"CategoryName": "Meat/Poultry"
}, {
"CategoryID": 7,
"CategoryName": "Produce"
}, {
"CategoryID": 8,
"CategoryName": "Seafood"
}];
</script>
<style type="text/css">
.customer-photo {
display: inline-block;
width: 32px;
height: 32px;
border-radius: 50%;
background-size: 32px 35px;
background-position: center center;
vertical-align: middle;
line-height: 32px;
box-shadow: inset 0 0 1px #999, inset 0 0 10px rgba(0,0,0,.2);
margin-left: 5px;
}
.customer-name {
display: inline-block;
vertical-align: middle;
line-height: 32px;
padding-left: 3px;
}
.k-grid tr .checkbox-align {
text-align: center;
vertical-align: middle;
}
.product-photo {
display: inline-block;
width: 32px;
height: 32px;
border-radius: 50%;
background-size: 32px 35px;
background-position: center center;
vertical-align: middle;
line-height: 32px;
box-shadow: inset 0 0 1px #999, inset 0 0 10px rgba(0,0,0,.2);
margin-right: 5px;
}
.product-name {
display: inline-block;
vertical-align: middle;
line-height: 32px;
padding-left: 3px;
}
.k-rating-container .k-rating-item {
padding: 4px 0;
}
.k-rating-container .k-rating-item .k-icon {
font-size: 16px;
}
.dropdown-country-wrap {
display: flex;
flex-wrap: nowrap;
align-items: center;
white-space: nowrap;
}
.dropdown-country-wrap img {
margin-right: 10px;
}
#grid .k-grid-edit-row > td > .k-rating {
margin-left: 0;
width: 100%;
}
.k-grid .k-grid-search {
margin-left: auto;
margin-right: 0;
}
</style>
</div>
</body>
</html>
I have a Kendo Master/Detail grid (jquery) that expands all rows to reveal any child records upon page load to provide a grid with a set of default data. However, not all of the rows returned when expanded have child elements to display. I currently have a link provided in a column of the master row, the link is coded using a template:
{
template: `"<a class='_kwJISSearch' style='color:blue; text-decoration:underline; cursor: pointer;'>Edit Case Assignment</a>",`
width: "100px"
}
What I would like to know if I can change the text and what the link is pointing to on the master row if no child elements are returned? I have provided my code below, where I create the columns for the master first, then create the grid with a data-bound, lastly, I coded the detail:
function loadSearchGrid() {
searchOriginalColumnList = [
{
field: "CaseYear",
title: "Case Year",
type: "number",
width: "100px"
},
{
field: "CaseNumber",
title: "Case Number",
width: "100px"
},
{
field: "Full_Style",
title: "Style",
template: "<a href='/Cases/Views/CaseItems/ViewDocket?cy=#=CaseYear#&cn=#=CaseNumber#' target='_blank' style='color: blue; text-decoration:underline' ># if(Full_Style == null || Full_Style == '' ) {# N/A #} else{ # #:Full_Style# #} # </a>",
width: "250px"
},
{
field: "DispInfo",
title: "Disp Info",
width: "175px"
},
{
field: "Max_OA",
title: "OA Date",
format: "{0:MM/dd/yyyy}",
width: "100px"
},
{
field: "Max_Conf",
title: "Conf Date",
format: "{0:MM/dd/yyyy}",
width: "120px"
},
{
field: "Evote_Info",
title: "Evote",
template: "<a href=" + apiUrl +"JISReports/JIS_eVOTE&P_CASEYEAR=#=CaseYear#&P_CASENUMBER=#=CaseNumber#&rs:Command=Render' target='_blank' style='color:blue; text-decoration:underline; cursor: pointer;' ># if(Evote_Info == 'TRUE') {# Evote Info #} else{ # #} # </a>",
width: "100px"
},
{
field: "Ap_T_Related",
title: "Related Case",
//format: "{0:MM/dd/yyyy}",
width: "120px"
},
{
field: "Lead",
title: "Lead",
//format: "{0:MM/dd/yyyy}",
width: "100px"
},
{
field: "Not_Lead",
title: "Not Lead",
//format: "{0:MM/dd/yyyy}",
width: "100px"
},
{
//field: "Ap_T_Related",
//title: "Related Case",
//format: "{0:MM/dd/yyyy}",
template: /*"# if( getDetailGrids() == null ) {# Case Not Assigned #} else{# <a class='_kwJISSearch' style='color:blue; text-decoration:underline; cursor: pointer;'>Edit Case Assignment</a>#}#",//*/"<a class='_kwJISSearch' style='color:blue; text-decoration:underline; cursor: pointer;'>Edit Case Assignment</a>",
width: "100px"
},
];
var searchGridSavedColumns = utils.getGridSavedColumns(searchOriginalColumnList, config.gridSettingsKeys.jisSearch);
grid = $("#grid").kendoGrid({
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: localRoutes.searchUrl,
dataType: "json",
method: "POST",
data: function () {
model = {
PanelType: viewModel.get("selectedPanelType"),
DispFinalInfo: viewModel.get("selectedFinalDisp"),
AssgnComp: viewModel.get("selectedAssignComp"),
ShowComm: viewModel.get("selectedShowComm"),
SortResult: viewModel.get("selectedSortResult"),
Assignment_Select: viewModel.get("selectedAssgnTypes"),
Assignment_For: viewModel.get("selectedSuiteMate"),
SearchCY: viewModel.get("caseYear"),
SearchCN: $('#caseNumber').val(),
Style: viewModel.get("style"),
};
return model;
}
}
},
error: function (e) {
$.unblockUI();
},
pageSize: 50,
schema: {
model: {
id: "CaseUaId",
fields: {
CaseUaId: { type: "string" },
PanelTypes: { type: "string" },
FinalDisp: { type: "string" },
AssignComp: { type: "string" },
ShowComm: { type: "string" },
SortResult: { type: "string" }
}
},
},
}),
pageable: {
refresh: true,
pageSizes: [20, 50, 100, 500]
},
toolbar: ["excel"],
editable: false,
groupable: true,
selectable: true,
filterable: true,
columnMenu: true,
scrollable: true,
reorderable: true,
resizable: true,//setting to allow column headers to be resizeable
autoBind: false,
sortable: {
mode: "multiple",
allowUnsort: true
},
toolbar: kendo.template($("#toolbar").html()),
excel: {
fileName: "JIS Search.xlsx",
allPages: true
},
//Second set of code for Master Detail
detailInit: detailInit,
dataBound: function (e) {
this.expandRow(this.tbody.find("tr.k-master-row"));//.first());
},
columns: (!!searchGridSavedColumns) ? searchGridSavedColumns : searchOriginalColumnList,
}).data("kendoGrid");
///Code to set the column headers as tooltips
grid.thead.kendoTooltip({
filter: "th",
content: function (e) {
var target = e.target;
return $(target).text();
}
});
$("#grid").on("click", "._kwJISSearch", function (e) {
e.preventDefault();
var ca = grid.dataItem($(e.currentTarget).closest("tr"));
var win = $("#_kwJISSearch").data("kendoWindow");
win.title();
win.content("");
win.refresh("/JIS/JISAssignment" +
"?cy=" + ca.CaseYear +
"&cn=" + ca.CaseNumber);
win.center().open().maximize();
});
searchGridSettingsViewModel = utils.createGridSettingsVM("Search Grid Settings", "grid", config.gridSettingsKeys.jisSearch, "gridSettingsTmpl", "gridSettingsDialog", true, true, true, true, 20);
kendo.bind($("#grid").find(".k-grid-toolbar"), searchGridSettingsViewModel);
searchGridLoaded = true;
}//end assignment grid creation
function detailInit(e) {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: {
//type: "odata",
transport: {
read: {
url: localRoutes.searchAssgnUrl,
dataType: "json",
method: "POST",
data: {
cy: e.data.CaseYear,
cn: e.data.CaseNumber,
showHis: viewModel.get("selectedAssignComp"),
caseY: viewModel.get("caseYear"),
caseN: viewModel.get("caseNumber")
}
}
},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 10,
filter: { field: "Case_Ua_Id", operator: "eq", value: e.data.CaseUaId }
},
scrollable: false,
sortable: true,
pageable: true,
columns: [
//{ field: "CaseUaId", width: "110px" },
{
field: "UserName", title: "User Name",
template: "# if(AssignEndDate == 'Incomplete' ) {# <span style='color:red; font-weight: bold'> #:UserName# </span> #} else{ # #:UserName# #} # ",
width: "70px"
},
{
field: "ReasonDesc", title: "Reason Desc",
template: "# if(ReasonDesc == 'EXPEDITED' || ReasonDesc == 'WALK' ) {# <span style='color:red; font-weight: bold'> #:ReasonDesc# </span> #} else{ # #:ReasonDesc# #} # ",
width: "70px"
},
{ field: "AssignBeginDate", title: "Begin Date", width: "70px" },
{
field: "AssignEndDate", title: "End Date",
template: "# if(Status_Code == 'PENDINGREVIEW' ) {# #:AssignEndDate# <span style='color:blue; font-style: italic'> (Pending Review) </span> #} else{ # #:AssignEndDate# #} # ",
width: "70px"
},
{ field: "DueDate", title: "Due Date", width: "70px" },
{ field: "AssignForLocID", title: "Assignment For", width: "100px" },
{ field: "AssignedByLocID", title: "Assigned By", width: "100px" },
{ field: "Comments", title: "Comments", width: "110px" },
]
});
}//end Case Assignment Detail Grid
You can use JavaScript code inside a template, e.g.:
template: "<a class='_kwJISSearch' style='color:blue; text-decoration:underline; cursor: pointer;'># if (data.childrenProperty && data.childrenProperty.length) { ##Edit Case Assignment## } else { ##No children text here ## } #</a>",
Assuming your master row has an array property for children.
I am using kendo grid with MVC in a .NET project. Two columns of my grid are templates and those have an input text inside of the template. That way every time the grid loads the input texts are always visible and available for change.
When the user clicks on save, I need to check all the rows of the grid, at client side and get the values of those two columns (the only two have templates) and get the values of the input box. So the result I am expecting is a list with two columns that have the last values inserted by the user in the input boxes and not the original value.
Here is my code:
//Grid Data source
var dataSource = new kendo.data.DataSource({
transport: {
read: { url: "/CsmForecastRegistration/GetForecast", cache: false }
},
error: function (e) {
openDialog(e.errorThrown);
},
batch: true,
pageSize: 20,
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "ForecastItemId",
fields: {
ForecastItemId: { editable: false },
RecordId: { editable: false },
SaleId: { editable: false },
IsUpSell: { editable: false },
BusinessName: { editable: false },
HealthScore: { editable: false },
CurrencySymbol: { editable: false },
ForecastWeekTotalContractValue: { editable: true },
ForecastWeekMonths: { editable: true },
ForecastWeek12Months: { editable: false }
}
}
}
});
$("#grdCsmForecast").kendoGrid({
dataSource: dataSource,
scrollable: true,
dataBound: onDataBound,
toolbar: ["excel"],
excel: {
allPages: true,
fileName: "CSMForecast.xlsx"
},
pageable: true,
columns: [
{ title: "", width: "80px", template: $("#comments-template").html(), attributes: { style: "text-align:center; background-color: white;" } },
{
title: "Contract Details",
columns: [
{ field: "RecordId", title: "RecordId", width: "90px", attributes: { "class": "contractDetailGridStyle" } },
{ field: "SaleId", title: "SaleId", width: "90px", attributes: { "class": "contractDetailGridStyle" } },
{ field: "IsUpSell", title: "Upsell?", width: "75px", attributes: { "class": "contractDetailGridStyle" } },
{ field: "BusinessName", title: "Business Name", width: "250px", attributes: { "class": "contractDetailGridStyle"} },
{ field: "HealthScore", title: "Health Score", width: "95px", attributes: { "class": "contractDetailGridStyle"} },
{ field: "CurrencySymbol", title: "CCY", width: "50px", attributes: { "class": "contractDetailGridStyle" } }
]
},
{
title: "Forecast Week",
columns: [
{ field: "ForecastWeekTotalContractValue", title: "TCV", width: "75px", template: $("#forecast-week-tcv").html(), attributes: { "class": "forecastWeekGridStyle" }, footerTemplate: "#: sum # " },
{ field: "ForecastWeekMonths", title: "Months", width: "70px", template: $("#forecast-weekMonths").html(), attributes: { "class": "forecastWeekGridStyle" } },
{ field: "ForecastWeek12Months", title: "12Month", width: "75px", attributes: { "class": "forecastWeekGridStyle" }, footerTemplate: "#: sum # " }
]
}
]
});
And the templates:
<script id="forecast-week-tcv" type="text/x-kendo-template">
# if(IsNewContract === true ){ #
<span>#=ForecastWeekTotalContractValue#</span>
#}
else{#
<input type="text" value="#=ForecastWeekTotalContractValue#" />
#}#
</script>
<script id="forecast-weekMonths" type="text/x-kendo-template">
# if(IsNewContract === true ){ #
<span>#=ForecastWeekMonths#</span>
#}
else{#
<input type="text" value="#=ForecastWeekMonths#" />
#}#
</script>
So I would like to have a list and send to my MVC the controller all the values of these two inputs:
<input type="text" value="#=ForecastWeekTotalContractValue#" />
<input type="text" value="#=ForecastWeekMonths#" />
Thanks
Try something like this:
function getInputValues() {
let result = [];
$('#grid tbody tr').each((i, tr) => {
let row = {};
$(tr).find('input[type="text"]').each((index, input) => {
row[(index ? "ForecastWeekTotalContractValue" : "ForecastWeekMonths")] = $(input).val();
});
result.push(row);
});
return result;
}
Demo
It just iterates over the elements and adds to an array of objects.
I have dropdown list from sorting grid. I want to manage same grid with pie chart, but I can't bound remote data to the piechart. The piechart must to show categories (the same role, like a dropdown list), but I can't bound to hierarchical remote data.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="styles/kendo.common.min.css" />
<link rel="stylesheet" href="styles/kendo.default.min.css" />
<script src="js/jquery.min.js"></script>
<script src="js/kendo.all.min.js"></script>
</head>
<body>
<div id="project">
<div id="grid"></div>
<div id="chart"></div>
<script type="text/x-kendo-template" id="template">
<div class="toolbar">
<label class="category-label" for="category">Show products by category:</label>
<input type="search" id="category" style="width: 150px"/>
</div>
</script>
<script>
$(document).ready(function() {
//Grid displays all products or products from one category, which set from dropdown list
var grid = $("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "//demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
},
pageSize: 20,
serverPaging: true,
serverSorting: true,
serverFiltering: true
},
toolbar: kendo.template($("#template").html()),
height: 550,
sortable: true,
pageable: true,
dataBound:function(){
var grid = this;
$.each(grid.tbody.find('tr'),function(){
var model = grid.dataItem(this);
if(model.Discontinued==true){
$('[data-uid='+model.uid+']').addClass('k-state-selected');
}
});
},
columns: [
// { field: "ProductID", title: "Product ID", width: 100 },
{ field: "ProductName", title: "Product Name", template: '#=kendo.format(ProductName.toUpperCase())#' },
{ field: "UnitPrice", title: "Price", width: 150, template: 'EUR #: kendo.format("{0:c}", UnitPrice)#' },
{ field: "UnitsInStock", title: "In Stock", width: 150 },
{ field: "Discontinued", title: "Discontinued", width:50 },
{ field: "QuantityPerUnit", title: "Quantity" }
]
});
//DropDown list for sorting by the category
var dropDown = grid.find("#category").kendoDropDownList({
dataTextField: "CategoryName",
dataValueField: "CategoryID",
autoBind: false,
optionLabel: "All",
dataSource: {
type: "odata",
severFiltering: true,
transport: {
read: "//demos.telerik.com/kendo-ui/service/Northwind.svc/Categories"
}
},
change: function() {
var value = this.value();
if (value) {
grid.data("kendoGrid").dataSource.filter({ field: "CategoryID", operator: "eq", value: parseInt(value) });
} else {
grid.data("kendoGrid").dataSource.filter({});
}
}
});
var data = [
{
"source": "Hydro",
"percentage": 20,
},
{
"source": "Hydro",
"percentage": 20
},
{
"source": "Solar",
"percentage": 10
},
{
"source": "Nuclear",
"percentage": 30
}
];
var dataSource = new kendo.data.DataSource({
data: data,
group: {field: "source", aggregates: [{
field: "percentage", aggregate: "sum"
}]}
});
dataSource.read();
function getChartData() {
var chartData = [];
var view = dataSource.view();
for(var idx = 0; idx < view.length; idx++) {
chartData.push({
source: view[idx].value,
percentage: view[idx].aggregates.percentage.sum
});
}
return chartData;
}
//From This piechart I want to sorting grid
var chart = $("#chart").kendoChart({
title: {
text: "Categories and Products"
},
legend: {
position: "bottom"
},
dataSource: {
transport: {
read: function(e) {
e.success(getChartData());
}
}
},
series: [{
type: "pie",
field: "percentage",
categoryField: "source",
explodeField: "explode",
aggregate: "count",
labels: {
visible: true,
background: "transparent",
template: "#= category #: \n #= value#%"
}
}],
seriesClick: function(e){
$.each(e.sender.dataSource.view(), function() {
// Clean up exploded state
this.explode = false;
});
// Disable animations
e.sender.options.transitions = false;
// Explode the current slice
e.dataItem.explode = true;
e.sender.refresh();
}
});
});
</script>
<style>
#grid .k-grid-toolbar
{
padding: .6em 1.3em;
}
.category-label
{
vertical-align: middle;
padding-right: .5em;
}
#category
{
vertical-align: middle;
}
.toolbar {
float: center;
}
</style>
</div>
You can bind a kendo pie chart with remote data, I have done this many times in the past. Take a look at the following link for an example on how to achieve this.
Kendo pie chart - remote binding
I used JQX grid widget.And through a javascript i'm populating cell values.This works good for Firefox.But not working in Chrome.Here is the code i have used.
var objCredit = jQuery.parseJSON(returnText);
document.getElementById('txtCustNumber').value = objCredit.CustomerId;
$('[id$=txtCustNumber]').text(objCredit.CustomerId);
getCustomerDetails();
document.getElementById('cmbDocType').value = '3';
***documentGridContainer.jqxGrid('setcellvalue', 0, 'Amount', objCredit.Amount);***
Here is my Grid Definition.
var source1 = { totalrecords: 5, unboundmode: true, datatype: "json",
datafields: [
{ name: 'LineId' },
{ name: 'DistCode' },
{ name: 'distFinder' },
{ name: 'DistCodeDesc' },
{ name: 'RevAccount' },
{ name: 'revAccountFinder' },
{ name: 'RevAccDesc' },
{ name: 'Amount', type: 'float' },
{ name: 'PrintComment' },
{ name: 'Comment' },
{ name: 'Discountable', type: 'string' },
{ name: 'OptionalField' },
{ name: 'optionalFieldFinder' }
],
localdata: data
};
var dataAdapter1 = new $.jqx.dataAdapter(source1);
documentGridContainer.jqxGrid(
{
width: 975,
source: dataAdapter1,
theme: '',
editable: true,
enabletooltips: true,
columnsresize: true,
autoheight: true,
selectionmode: 'singlecell',
columns: [
{ text: 'Line Number', columntype: 'textbox', datafield: 'LineId', width: 100, editable: false },
{ text: 'Dist.Code', columntype: 'textbox', datafield: 'DistCode', width: 80 },
{ text: '', datafield: 'distFinder', columntype: 'button', width: 30, resizable: false, cellsrenderer: function () { },
buttonclick: function (row) {
editrow = row;
showDocumentDistFinder(editrow);
}
},
{ text: 'Description', datafield: 'DistCodeDesc', columntype: 'textbox', width: 150, editable: false },
{ text: 'Revenue Account', datafield: 'RevAccount', columntype: 'textbox', width: 150 },
{ text: '', datafield: 'revAccountFinder', columntype: 'button', width: 30, resizable: false, cellsrenderer: function () { },
buttonclick: function (row) {
editrow = row;
showDocumentRevenueFinder(editrow);
}
},
{ text: 'Acc. Description', datafield: 'RevAccDesc', columntype: 'textbox', width: 150, editable: false },
{ text: 'Amount', datafield: 'Amount', cellsformat: 'f2', cellsalign: 'right', align: 'right', width: 80, editable: setAmountEditable() },
//{ text: 'Print Comment', datafield: 'PrintComment', width: 150 },
{text: 'Prt Comment', datafield: 'PrintComment', width: 93, columntype: 'dropdownlist',
createeditor: function (row, column, editor) {
// assign a new data source to the dropdownlist.
var list = ['Yes', 'No'];
editor.jqxDropDownList({ source: list });
},
// update the editor's value before saving it.
cellvaluechanging: function (row, column, columntype, oldvalue, newvalue) {
// return the old value, if the new value is empty.
if (newvalue == "") return oldvalue;
}
},
{ text: 'Comment', datafield: 'Comment', width: 250 },
//{ text: 'Discountable', datafield: 'Discountable', width: 100 }
{text: 'Discountable', datafield: 'Discountable', width: 93, columntype: 'dropdownlist',
createeditor: function (row, column, editor) {
// assign a new data source to the dropdownlist.
var list = ['Yes', 'No'];
editor.jqxDropDownList({ source: list });
},
// update the editor's value before saving it.
cellvaluechanging: function (row, column, columntype, oldvalue, newvalue) {
// return the old value, if the new value is empty.
if (newvalue == "") return oldvalue;
}
},
{ text: 'Optional Field', datafield: 'OptionalField', width: 100 },
{ text: '', datafield: 'optionalFieldFinder', columntype: 'button', width: 30, cellsrenderer: function () { },
buttonclick: function (row) {
editrow = row;
createDocumentOptionalFields(editrow);
$('#model-documentOptionField').modal('show');
}
}
]
});
Thanks in advance
Your initialization is incorrect. datatype: "json" in unbound mode does not make sense. You should remove that. Below is a working sample:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="../../scripts/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxlistbox.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxdropdownlist.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxmenu.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.selection.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.edit.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.sort.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.columnsresize.js"></script>
<script type="text/javascript" src="../../scripts/gettheme.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var source1 = {
totalrecords: 5, unboundmode: true,
datafields: [
{ name: 'LineId' },
{ name: 'DistCode' },
{ name: 'distFinder' },
{ name: 'DistCodeDesc' },
{ name: 'RevAccount' },
{ name: 'revAccountFinder' },
{ name: 'RevAccDesc' },
{ name: 'Amount', type: 'float' },
{ name: 'PrintComment' },
{ name: 'Comment' },
{ name: 'Discountable', type: 'string' },
{ name: 'OptionalField' },
{ name: 'optionalFieldFinder' }
]
};
var dataAdapter1 = new $.jqx.dataAdapter(source1);
var documentGridContainer = $("#jqxgrid");
documentGridContainer.jqxGrid(
{
width: 975,
source: dataAdapter1,
theme: '',
editable: true,
enabletooltips: true,
columnsresize: true,
ready: function()
{
documentGridContainer.jqxGrid('setcellvalue', 0, 'Amount', 50);
},
autoheight: true,
selectionmode: 'singlecell',
columns: [
{ text: 'Line Number', columntype: 'textbox', datafield: 'LineId', width: 100, editable: false },
{ text: 'Dist.Code', columntype: 'textbox', datafield: 'DistCode', width: 80 },
{
text: '', datafield: 'distFinder', columntype: 'button', width: 30, resizable: false, cellsrenderer: function () { },
buttonclick: function (row) {
editrow = row;
showDocumentDistFinder(editrow);
}
},
{ text: 'Description', datafield: 'DistCodeDesc', columntype: 'textbox', width: 150, editable: false },
{ text: 'Revenue Account', datafield: 'RevAccount', columntype: 'textbox', width: 150 },
{
text: '', datafield: 'revAccountFinder', columntype: 'button', width: 30, resizable: false, cellsrenderer: function () { },
buttonclick: function (row) {
editrow = row;
//showDocumentRevenueFinder(editrow);
}
},
{ text: 'Acc. Description', datafield: 'RevAccDesc', columntype: 'textbox', width: 150, editable: false },
{ text: 'Amount', datafield: 'Amount', cellsformat: 'f2', cellsalign: 'right', align: 'right', width: 80, editable: true },
//{ text: 'Print Comment', datafield: 'PrintComment', width: 150 },
{
text: 'Prt Comment', datafield: 'PrintComment', width: 93, columntype: 'dropdownlist',
createeditor: function (row, column, editor) {
// assign a new data source to the dropdownlist.
var list = ['Yes', 'No'];
editor.jqxDropDownList({ source: list });
},
// update the editor's value before saving it.
cellvaluechanging: function (row, column, columntype, oldvalue, newvalue) {
// return the old value, if the new value is empty.
if (newvalue == "") return oldvalue;
}
},
{ text: 'Comment', datafield: 'Comment', width: 250 },
//{ text: 'Discountable', datafield: 'Discountable', width: 100 }
{
text: 'Discountable', datafield: 'Discountable', width: 93, columntype: 'dropdownlist',
createeditor: function (row, column, editor) {
// assign a new data source to the dropdownlist.
var list = ['Yes', 'No'];
editor.jqxDropDownList({ source: list });
},
// update the editor's value before saving it.
cellvaluechanging: function (row, column, columntype, oldvalue, newvalue) {
// return the old value, if the new value is empty.
if (newvalue == "") return oldvalue;
}
},
{ text: 'Optional Field', datafield: 'OptionalField', width: 100 },
{
text: '', datafield: 'optionalFieldFinder', columntype: 'button', width: 30, cellsrenderer: function () { },
buttonclick: function (row) {
editrow = row;
createDocumentOptionalFields(editrow);
$('#model-documentOptionField').modal('show');
}
}
]
});
});
</script>
</head>
<body class='default'>
<div id='jqxWidget'>
<div id="jqxgrid">
</div>
</div>
</body>
</html>