Kendo Grid , Show different template in detail grid based on condition - javascript

I am using kendo grid and its working fine . I need to check each row of my grid that if it contains a specific value then bind data using one template otherwise the template will be different . Is this possible ? Here is my code
function detailInit(e) {
var isCreateGrid = true;
var masterRowId = e.data.uid;
var data = [];
$.ajax({
type: "GET",
url: 'https://www.domain.com/details?&transactionId=' + e.data.TransactionId,
contentType: "application/json; charset=utf-8",
dataType: 'json',
headers: { 'ccode': compCode },
cache: false,
async: false,
success: function (result) {
var jsonResult = JSON.parse(result);
for (var i = 0; i < jsonResult.length; i++) {
if (jsonResult[i]["OldValue"] == null || jsonResult[i]["OldValue"] == '')
isCreateGrid = true;
else {
isCreateGrid = false;
break;
}
}
if (isCreateGrid) {
for (var i = 0; i < jsonResult.length; i++) {
data.push({ FieldUpdated: jsonResult[i]["ChangeColumns"], Value: jsonResult[i]["NewValue"] });
}
} else {
for (var i = 0; i < jsonResult.length; i++) {
data.push({ FieldUpdated: jsonResult[i]["ChangeColumns"], Was: jsonResult[i]["OldValue"], Now: jsonResult[i]["NewValue"] });
}
}
}
});
var dataSource = new kendo.data.DataSource({ data: data });
if (data.length == 0) {
var grid = $("#logs").data("kendoGrid");
grid.collapseRow("[data-uid='" + masterRowId + "']");
grid.dataSource.read();
} else {
if (isCreateGrid) {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: dataSource,
filter: { field: e.data.Log, operator: "contains", value: 'has created' },
columns:
[{ field: "FieldUpdated", title: "Field Updated", width: "50px" },
{ field: "Value", title: "Value", width: "50px" }]
});
} else {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: dataSource,
filter: { field: e.data.Log, operator: "contains", value: 'has created' },
columns:
[{ field: "FieldUpdated", title: "Field Updated", width: "50px" },
{ field: "Was", title: "Was", width: "50px" },
{ field: "Now", title: "Now", width: "50px" }]
});
}
}
}
but this isCreateGrid condition seems to be useless because if he finds any row where isCreateGrid criteria is false then all rows will have template against false criteria .

Yes you can. Kindly refer below code.
$(gridId).kendoGrid({
dataSource: {
data: datasource
},
scrollable: true,
sortable: true,
resizable: true,
columns: [
{ field: "MetricName", title: "Metric", width: "130px" },
{ field: "OnTrack", title: "On Track", template:'#:changeTemplate(OnTrack)#', width: "130px", attributes: { style: "text-align: center !important;" } },
{ field: "CurrentAmount", title: "Current", template: '$ #:parseFloat(CurrentAmount).toFixed(2)#', width: "130px" },
{ field: "RequiredAmount", title: "Required", template: '$ #:parseFloat(RequiredAmount).toFixed(2)#', width: "130px" }
]
});
function changeTemplate(value)
{
Conditions depending on Your Business Logic
if ()
return "HTML Here";
else
return "HTML Here";
}

Related

How to get selected row and its dataItem in the KendoUI?

this is my Kendo Grid
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/Actionables/GetAccessibleTemplateForAssets/",
data: { assetID: '#Model.AssetID', types: '#Model.TypeName' },
dataType:"Json",
type: "GET"
},
},
schema: {
model: {
id: "ID",
fields: {
ID: { type: "int" },
Name: { type: "string" },
Description: { type: "string" },
Types: { type: "string" },
EntryGroupID: {type:"int"}
}
}
},
pageSize: 3,
});
$("#grid").kendoGrid({
dataSource: dataSource,
dataBound: onDataBound,
autoSync: true,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
height: 250,
sortable: true,
filterable: {
mode: "row"
},
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns:
[{
field: "Types",
width: 100,
title: "Type",
template: "<image src='/Content/Images/Pins/#:data.Types#.png'/>",
filterable: false
},{
field: "Name",
width: 150,
title: "Name",
filterable: {
cell: {
operator: "contains"
}
}
}, {
field: "Description",
width: 150,
title: "Description",
filterable: {
cell: {
operator: "contains"
}
}
},{
command: [
{ name: "remove", text: " ", click: removeTab, iconClass: "fa fa-trash" },
{ name:"view", text: " ", click: addTab , iconClass: "fa fa-plus-circle"}],
title: "Action",
width: 100,
}],
editable: {
mode:"popup"
},
}).data("kendoGrid");
wnd = $("#details").kendoWindow({
title: "View Tab",
modal: true,
visible: false,
resizable: false,
width: 300
}).data("kendoWindow");
detailsTemplate = kendo.template($("#ViewDetails").html());
this will get called when user clicked '+' sign in command column. it opens a popup window.
function addTab(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
}
the popup window contains two button, on that button click event OpenRecentlyClosed() function will get called.
<script type="text/x-kendo-template" id="ViewDetails">
<div id="details-container">
<button id="oldEntryGroup" class="k-button" onclick="OpenRecentlyClosed()">Open recently closed</button>
<br /><br />
<button id="NewEntryGroup" class="k-button">Open new</button>
</div>
the below function I'm trying to access dataItem of clicked/selected row. please help. thank you in advance
function OpenRecentlyClosed() {
//trying to access dataItem here.. please help
//var grid = $("#grid").data("kendoGrid");
//var dataItem = grid.dataItem(grid.select());
$.ajax({
cache: false,
type: "GET",
url: "some url",
data: {x: dataItem.ID},// need to pass value of dataItem.ID
success: function () {
//my code
}
});
}
Event to capture row click and get data from that row:
$(document).on("click", "#grid tbody tr", function (e) {
var element = e.target || e.srcElement;
var data = $("#grid").data("kendoGrid").dataItem($(element).closest("tr"));
});
I think you need to keep a reference to the selected dataItem in your javacript function addTab.
function addTab(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
wnd.selectedDataItem = dataItem;
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
}
Then in OpenRecentlyClosed you could access the dataItem.
function OpenRecentlyClosed() {
var dataItem = wnd.selectedDataItem;
$.ajax({
cache: false,
type: "GET",
url: "some url",
data: {x: dataItem.ID},// need to pass value of dataItem.ID
success: function () {
//my code
}
});
}
Please try with the below code snippet.
function OpenRecentlyClosed() {
var grid = $("#grid").data("kendoGrid");
var selectedRows = grid.select();
selectedRows.each(function(index, row) {
var selectedItem = grid.dataItem(row);
alert(selectedItem.ID);
});
...
...
}
Let me know if any concern.
Note: grid.dataItem(row) will just get what's in the row. If you have a database and really want the dataItem and maybe some items in another dataset that are in some relationship with your item, you can do e.g. an AjaxCall.

Kendo UI Grid Paging is not working

In document ready i append div inside body and i am creating a kendo ui window and then inside that window append second div with creating kendo dynamic chart or kendo grid.
When i create this things i'm loading data from AJAX and shows grid normally, but paging and column resizing is not working
Can you help me on this situation?
Here my code
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
url: '../Home/GetChartsAndInformations',
success: function (data) {
for (i = 1; i <= data.length; i++) {
count = data.length;
$("body").append('<div class="chartWindow" id="chartWindow-' + i + '"><div id="chart-' + i + '"></div></div>');
var myWindow = $('#chartWindow-' + i).kendoWindow().getKendoWindow();
myWindow.setOptions({
width: data[i - 1].Width,
height: data[i - 1].Height,
actions: ["Pin","Maximize", "Close"],
position: {
top: data[i - 1].Ypos,
left: data[i - 1].Xpos
},
title: data[i - 1].ChartDescription
});
$("#chart-" + i).append(FillWindowWithCharts(i))
}
}
});
});
function FillWindowWithCharts(number) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '../Home/QuerySelected',
data: { id: number },
success: function (data) {
if (data.length != 0) {
if (data[0].ChartType == "grid") {
myData = data;
createGrid(data[0].Id);
}
else {
if (data[0].IsGroup) {
myData = {
data: data,
group: {
field: data[0].GroupValue
},
sort: {
field: data[0].SortValue
}
}
ToolTipTemplate = "#= dataItem.Value1 #: #= kendo.format('{0:N}',value) #";
}
else {
myData = data
}
series = [{
field: data[0].SeriesField,
labels: {
visible: true
}
}];
categories = {
field: data[0].CategoryField
}
stackValue = data[0].IsStacked;
chartType = data[0].ChartType;
title = data[0].ChartDescription;
createChart(number);
}
}
else {
$("#chart-" + number).html("No Data in this interval!!");
}
}
});
}
function createGrid(number) {
$("#chart-" + number).kendoGrid({
dataSource: myData,
resizable: true,
pageable: {
refresh:true,
pageSize: 5
},
columns: [
{ field: "Value1", title: myData[0].Series1, hidden: myData[0].Series1 == null ? true : false },
{ field: "Value2", title: myData[0].Series2, hidden: myData[0].Series2 == null ? true : false },
{ field: "Value3", title: myData[0].Series3, hidden: myData[0].Series3 == null ? true : false },
{ field: "Value4", title: myData[0].Series4, hidden: myData[0].Series4 == null ? true : false },
{ field: "Value5", title: myData[0].Series5, hidden: myData[0].Series5 == null ? true : false }
]
});
}
function createChart(number) {
$("#chart-" + number).kendoChart({
theme: "metro",
dataSource:myData,
title: {
text: title
},
legend: {
visible: true,
position: "bottom",
labels: {
template: '#: chartType == "pie" ? dataItem.Value1 : chartType == "donut" ? dataItem.Value1 : text #'
}
},
seriesDefaults: {
type: chartType,
stack: stackValue
},
series: series,
valueAxis: {
labels: {
format: "{0}"
}
},
categoryAxis: categories,
tooltip: {
visible: true,
format: "{0}",
template: ToolTipTemplate
}
});
}
Thank you for your help
After i read some kendo dynamic grid data binding articles . I found way how to bind dynamically to grid some blog example
I give an example below
function createGrid(number,from,to) {
$("#grid").kendoGrid({
dataSource: {
type: "json",
serverPaging: false,
pageSize: 10,
transport: { //With the transform i can connect data from ajax
read: {
url: "../Home/QuerySelected",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
data: { id: number, from: from, to: to } // I can pass parameter
},
parameterMap: function (options) {
return JSON.stringify(options);
}
},
schema: { // Please be carefull because if you forget schema grid can give different errors. You need to write schema Data and Total and put right place in datasource
data: "Data",
total: "Total"
}
},
resizable: true,
pageable: {
refresh: true
},
sortable: true,
filterable: {
extra: false,
operators: {
string: {
startswith: "Starts with",
contains: "Contains"
}
}
},
columns: [
{ field: "Value1", title: myData.Data[0].Series1, hidden: myData.Data[0].Series1 == null ? true : false },
{ field: "Value2", title: myData.Data[0].Series2, hidden: myData.Data[0].Series2 == null ? true : false },
{ field: "Value3", title: myData.Data[0].Series3, hidden: myData.Data[0].Series3 == null ? true : false },
{ field: "Value4", title: myData.Data[0].Series4, hidden: myData.Data[0].Series4 == null ? true : false },
{ field: "Value5", title: myData.Data[0].Series5, hidden: myData.Data[0].Series5 == null ? true : false }
]
});
$(':contains("No Data in this interval!!")').each(function () {
$("#chart-" + number).html($("#chart-" + number).html().split("No Data in this interval!!").join(""));
});
Thanks!

Kendo Grid get row and column index on Change event

I have the following code:
function grd_onChange(e) {
var grid = $("#grd").data("kendoGrid");
var selectedCell = grid.select();
var index = selectedCell.index();
var row = selectedCell.closest("tr");
var col = selectedCell.closest("td");
alert(row);
}
I would like to know how can I get the column index when a user clicks on a cell of a particular row of the grid.
Please try with the below code snippet.
<body>
<script>
function onChange(arg) {
var grid = $("#Grid").data("kendoGrid");
var row = this.select().closest("tr");
var rowIdx = $("tr", grid.tbody).index(row);
var colIdx = this.select().index();
alert(rowIdx + '-' + colIdx);
}
$(document).ready(function () {
$("#Grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Orders",
dataType: "jsonp"
},
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
},
selectable: "multiple cell",
change: onChange,
filterable: true,
sortable: true,
pageable: true,
columns: [{
field: "OrderID",
filterable: false
},
"Freight",
{
field: "OrderDate",
title: "Order Date",
width: 120,
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name",
width: 260
}, {
field: "ShipCity",
title: "Ship City",
width: 150
}
]
});
});
</script>
<div id="Grid"></div>
</body>
OR
function onDataBound(e) {
var grid = $("#Grid").data("kendoGrid");
$(grid.tbody).on("click", "td", function (e) {
var row = $(this).closest("tr");
var rowIdx = $("tr", grid.tbody).index(row);
var colIdx = $("td", row).index(this);
alert(rowIdx + '-' + colIdx);
});
}
$(document).ready(function () {
$("#Grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Orders",
dataType: "jsonp"
},
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
},
dataBound: onDataBound,
filterable: true,
sortable: true,
pageable: true,
columns: [{
field: "OrderID",
filterable: false
},
"Freight",
{
field: "OrderDate",
title: "Order Date",
width: 120,
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name",
width: 260
}, {
field: "ShipCity",
title: "Ship City",
width: 150
}
]
});
});
<div id="Grid"></div>
Let me know if any concern.

Kendo Grid delete all column

I am working on Kendo Grid (sorting enabled). Delete event is working fine but once i delete all rows in kendo grid and again press column header it starts showing all deleted data. Anyone have idea what i am doing wrong
function GetManagePlanData(_data) {
$.each(_data, function (key, value) {
if (value.Bonus == 'False')
$('#chkBonusHeader').attr('checked', false);
else if (value.MeritIncrease == 'False')
$('#chkMeritIncHeader').attr('checked', false);
});
var isAllBonusSelected = true, isAllMeritSelected = true, isAllStockSelected = true;
$("#tblEligibleEmployees").kendoGrid({
dataSource: {
data:_data,
group: [{ field: "ManagerName" }],// Add manager name here
schema: {
model: {
fields: {
ManagerRelationRefID: { type: "string" },
EmployeeRelationRefID: { type: "string" },
ManagerName: { type: "string" },
EmployeeCode: { type: "string" },
FullName1: { type: "string" },
JoiningDate: { type: "string" },
BusinessUnitName: { type: "string" },
FTE: { type: "string" },
Salary: { type: "string" },
HourlyRate:{ type: "string" },
EmpStatus: { type: "string" },
MeritIncrease: { type: "bool" },
Bonus: { type: "bool" },
BonusTarget: { type: "double" },
Stock: { type: "bool" },
BonusBase: { type: "decimal" },
Delete : { type: "string" }
}
}
},
//pageSize: 20
},
scrollable: false,
sortable: true,
filterable: false,
groupable:false,
//pageable: {
// input: false,
// numeric: false
//},
columns: [
{ field: "ManagerName", hidden: true, title: "Manager Name" },//resource required manager name
{ field: "ManagerRelationRefID", hidden: true, template: "<input id=hdnManagerID#=EmployeeRelationRefID# value=#=ManagerRelationRefID# />" },
{ field: "EmployeeRelationRefID", hidden: true, template: "<input id=hdnEmployeeID#=EmployeeRelationRefID# value=#=EmployeeRelationRefID# />" },
{ field: "EmployeeCode", title: key_EmployeeId, width: "90px" },
{ field: "FullName1", title: key_fullname, width: "140px" },
{ field: "JoiningDate", title: key_hiredt, width: "110px" },
{ field: "BusinessUnitName", title: Key_Location, width: "90px" },
{
field: "Salary", title: key_Salary, width: "90px", template: FormatSalary
},
{
field: "HourlyRate", title: 'Hourly Rate', width: "90px", template: FormatHourlySalary
},
{ field: "FTE", title: Key_FTE, width: "80px" },
{ field: "EmpStatus", title: key_status, width: "70px" },
{
field: "MeritIncrease", title: key_MeritIncrease, template: ApplyMeritChecks, width: "100px",
hidden: (isMeritIncrease == 0 ? true : false),
headerTemplate: '<input type="checkbox" id="chkMeritIncHeader" >' + key_MeritIncrease + ' </input>',
sortable:false
},
{
field: "Bonus", title: key_Bonus, template: ApplyBonusChecks, width: "100px",
hidden : (isBonus==0 ? true:false),
headerTemplate: '<input type="checkbox" id="chkBonusHeader">' + key_Bonus + ' </input>',
sortable: false
},
{ field: "BonusTarget", title: key_BonusTarget, template: FormatBonusTarget, width: "70px", hidden : (isBonus==0 ? true:false) },
{
field: "Stock", title: key_Stock, template: ApplyStockChecks, width: "60px",
hidden: (isStock == 0 ? true : false),
headerTemplate: '<input type="checkbox" id="chkStockHeader" /><label>' + key_Stock + '</label>'
},
{
field:"BonusBase",title:"Bonus Base" ,width:"80px",
template:ApplyBonusBase,
sortable:false
},
{
field:"Delete",title:"",width :"80px",template:ApplyDelete,sortable:false
}
]
}).data("kendoGrid");
$('.k-grid-header .k-header').css('font-weight', 'bold');
$('.k-header[data-field="Delete"]').css('text-indent', '-9999px');
}
function deleteRow(ID) {
jConfirm2(key_Yes, key_No, key_PlanDeleteMsg, "", function (r) {
if (r == true) {
var nxtRow = $('#btndelete-' + ID).parent().parent().next('tr').hasClass("k-grouping-row");
var prvRow = $('#btndelete-' + ID).parent().parent().prev('tr').hasClass("k-grouping-row");
var nxtRowlength = $('#btndelete-' + ID).parent().parent().next('tr').length
// if ((nxtRow || nxtRowlength == 0) && prvRow) {
//var rowToDelete = $('#btndelete-' + ID).parent().parent().prev('tr');
var nextRow = $('#btndelete-' + ID).parent().parent().closest('tr');
var grid = $("#tblEligibleEmployees").data("kendoGrid");
// grid.removeRow(rowToDelete);
grid.removeRow(nextRow);
}
});
}
Do let me know what i am doing wrong my?
Please try refreshing the kendo grid after deleting the record. Following is the code.
$('#GridName').data('kendoGrid').refresh();
We are removing data from Kendo datasource not from database. Our working Code is
if ($('#tblEligibleEmployees').data('kendoGrid').dataSource._data.length == 0) {
$('#tblEligibleEmployees').data().kendoGrid.destroy();
return false;
}
On getting length 0 from kendo datasource destroying kendo grid.

Kendo UI Grid - How do I pass a selected item ID to an MVC view containing another grid?

I've followed this example from the Kendo UI Web Grid code library. I'm looking to modify the existing JavaScript and replace the alert with a method to send the selected item ID to another view with a slightly different grid. Here is the code from the example. Any suggestions?
<div id="grid"></div>
<button id="showSelection">Show selected IDs</button>
<script>
$(document).ready(function () {
//DataSource definition
var crudServiceBaseUrl = "http://demos.kendoui.com/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: {
editable: false,
nullable: true
},
ProductName: {
validation: {
required: true
}
},
UnitPrice: {
type: "number",
validation: {
required: true,
min: 1
}
},
Discontinued: {
type: "boolean"
},
UnitsInStock: {
type: "number",
validation: {
min: 0,
required: true
}
}
}
}
}
});
//Grid definition
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
//define dataBound event handler
dataBound: onDataBound,
toolbar: ["create"],
columns: [
//define template column with checkbox and attach click event handler
{ template: "<input type='checkbox' class='checkbox' />" },
"ProductName", {
field: "UnitPrice",
title: "Unit Price",
format: "{0:c}",
width: "100px"
}, {
field: "UnitsInStock",
title: "Units In Stock",
width: "100px"
}, {
field: "Discontinued",
width: "100px"
}, {
command: ["edit", "destroy"],
title: " ",
width: "172px"
}
],
editable: "inline"
}).data("kendoGrid");
//bind click event to the checkbox
grid.table.on("click", ".checkbox" , selectRow);
$("#showSelection").bind("click", function () {
var checked = [];
for(var i in checkedIds){
if(checkedIds[i]){
checked.push(i);
}
}
alert(checked);
});
});
var checkedIds = {};
//on click of the checkbox:
function selectRow() {
var checked = this.checked,
row = $(this).closest("tr"),
grid = $("#grid").data("kendoGrid"),
dataItem = grid.dataItem(row);
checkedIds[dataItem.id] = checked;
if (checked) {
//-select the row
row.addClass("k-state-selected");
} else {
//-remove selection
row.removeClass("k-state-selected");
}
}
//on dataBound event restore previous selected rows:
function onDataBound(e) {
var view = this.dataSource.view();
for(var i = 0; i < view.length;i++){
if(checkedIds[view[i].id]){
this.tbody.find("tr[data-uid='" + view[i].uid + "']")
.addClass("k-state-selected")
.find(".checkbox")
.attr("checked","checked");
}
}
}
</script>

Categories