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

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.

Related

Devexpress AngularJS get dynamic data for Pivot

In my AngularJS web app, I'm doing a Pivot with devexpress. Particularly, I'm using
the Field Chooser: https://js.devexpress.com/Demos/WidgetsGallery/Demo/PivotGrid/FieldChooser/AngularJS/Light/
In the example there are static data. I have to retrieve them from the server. So, I wrote this:
$scope.testData = null;
$scope.pivotGridDataSource = new DevExpress.data.PivotGridDataSource({
fields: [{
caption: "Nome",
dataField: "fullName",
area: "row"
}, {
caption: "Country",
dataField: "country",
area: "column"
}, {
caption: "Count",
dataField: "countOne",
dataType: "number",
summaryType: "sum",
area: "data"
}],
store: $scope.testData
});
$scope.pivotGridOptions = {
allowSortingBySummary: true,
allowSorting: true,
allowFiltering: true,
showBorders: true,
dataSource: $scope.pivotGridDataSource,
fieldChooser: {
enabled: false
}
},
$scope.fieldChooserOptions = {
dataSource: $scope.pivotGridDataSource,
texts: {
allFields: "All",
columnFields: "Columns",
dataFields: "Data",
rowFields: "Rows",
filterFields: "Filter"
},
width: 400,
height: 400,
bindingOptions: {
layout: "layout"
}
};
// Now I call the function to retrieve data
$scope.getTestData = () => {
// I call the server and save the data
........
$scope.testData = result;
}
The problem is that the table, after the calling, is still empty. There is written "No data". Why? I also tried to write
$scope.pivotGridDataSource.load();
$scope.pivotGridDataSource.reload();
after the call to the server, but it doesn't work yet.
The problem is in your store, so do something like this
var dataStore = new DevExpress.data.CustomStore({
load: function (loadOptions) {
var d = $.Deferred();
$.ajax({
url: UrlApi,
method: "GET",
}).done(function (result) {
d.resolve(result, {
});
});
return d.promise();
},
key: "Id",
});
$scope.pivotGridDataSource = new DevExpress.data.PivotGridDataSource({
.......
store: dataStore
});
See this code below, it is jquery, but AngularJS is basically the same
var dataStore = new DevExpress.data.CustomStore({
load: function (loadOptions) {
var d = $.Deferred();
$.ajax({
url: UrlApi,
method: "GET",
}).done(function (result) {
d.resolve(result, {
});
});
return d.promise();
},
key: "Id",
});
$("#pvtSales").dxPivotGrid({
showBorders: true,
"export": {
enabled: true,
fileName: "Sales"
},
dataSource: {
fields: [{
caption: "Fecha",
dataField: "maeFecha",
width: 350,
area: "row"
}, {
caption: "Nombre",
dataField: "maeNombre",
dataType: "number",
summaryType: "count",
area: "data"
}, {
dataField: "maeGestion",
width: 350,
area: "column"
}],
store: dataStore
}
});
And see the results

how to use custom command buttons in kendo grid with ajax call using javascript

i have the problem to use the custom command buttons in kendo grid with ajax call using javascript call web api post action with dynamic parameters behind buttons click(start,Stop,Restart)
datasource
dataSource = new kendo.data.DataSource({
transport: {
read:
{
url: crudServiceBaseUrl + "WindowsService",
dataType: "json",
},
destroy:
{
url: crudServiceBaseUrl + "WindowsService/Delete/?deletedby=" + clientid,
type: "DELETE"
},
create:
{
url: crudServiceBaseUrl + "WindowsService/Post",
type: "POST"
//complete: function (e) {
// $("#grid").data("kendoGrid").dataSource.read();
//}
},
update:
{
url: crudServiceBaseUrl + "WindowsService/Put/",
type: "PUT",
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
},
schema:
{
model:
{
id: "WindowsServiceId",
fields: {
WindowsServiceId: { editable: true, nullable: false, type: "int" },
ServiceName: { editable: true, nullable: true, type: "string" },
ServiceStatus: { editable: true, nullable: false, type: "string" },
}
}
}
});
kendo grid
$("#grid").kendoGrid({
dataSource: dataSource,
editable: "popup",
toolbar: ["create"],
columns: [
{
field:"ServiceName",
title: "Service",
width: '200px',
},
{
field: "ServiceStatus",
title: "Status",
width: '140px',
},
{
field: "CreatedDate",
title: "Date",
width: '140px',
},
{
command: [
{
name: "start",
text: "Start",
click: function (e) {
$.ajax({
method: "POST",
url: crudServiceBaseUrl + "WindowsService/Start?windowsserviceid=3c661827-01cf-e511-bcd8-3859f9fd735e"+"&clientid="+clientid
}).done(function (msg) {
alert("Service Started successfully");
}).fail(function () {
alert("service failed");
});
}
},
{
name: "stop",
text: "Stop",
click: function (e) {
$.ajax({
method: "POST",
url: crudServiceBaseUrl + "WindowsService/Stop?windowsserviceid=3c661827-01cf-e511-bcd8-3859f9fd735e"+"&clientid="+clientid
}).done(function (msg) {
alert("Service Stop successfully");
}).fail(function () {
alert("service failed");
});
}
},
{
name: "restart",
text: "Restart",
click: function (e) {
$.ajax({
method: "POST",
url: crudServiceBaseUrl + "WindowsService/ReStart?windowsserviceid=3c661827-01cf-e511-bcd8-3859f9fd735e"+"&clientid="+clientid
}).done(function (msg) {
alert("Service ReStarted successfully");
}).fail(function () {
alert("service failed");
});
}
},
{
name: "history",
text: "History",
click: function (e) {
alert("History");
}
}
]
}
],
//height: "500px",
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
}).data("kendoGrid")
;
html
<div id="grid"> </div>
i have the problem to pass the dynamic windowsserviceid which is unique id, now i just use the static id. its working with static value.
please help/guide me how to use the dynamic windowsserviceid in ajax function call. i appreciate your valuable time and effort. thanks in advance.
Finally I found the solution by accessing the Unique Id of row and then using that Id in my Button Clicks functions and it all worked for me perfect.
var tr = $(e.target).closest("tr"); //accessing a row in grid
var item = this.dataItem(tr); //accessing row items in the grid
var winServiceId = item.WindowsServiceId; //my Unique Id in a row
and finally used this winServiceId in my Button click functions.
This should work for you:
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [
{ hidden: true, field: "id" },
{ field: "name" }
],
dataSource: [ { id: 1, name: "Jane Doe" }, { id: 2, name: "John Doe" } ]
});
</script>
You can read more about it here:
http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#configuration-columns.headerAttributes
Then all you have to do is access the hidden field value in your function.
On another note, you should remove your functions from the grid definition and have them as separate functions that you call from within the grid def.

Kendo Grid, How to enable edit on next editable column pressing tab key?

I have a editable grid, which is editable after click on the selected cell.
I would like to ask:
Is possible to enable event that after tab is pressed, is edit mode moved into next editable field on same row?
Thanks for any help.
Set navigatable to true in the Grid initialization. The documentation says:
$(document).ready(function () {
var crudServiceBaseUrl = "http://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 7,
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").kendoGrid({
dataSource: dataSource,
pageable: true,
navigatable: true,
height: 550,
toolbar: ["save"],
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 120 },
{ field: "UnitsInStock", title: "Units In Stock", width: 120 }
],
editable: true
});
});
<link href="http://cdn.kendostatic.com/2014.2.1008/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2014.2.1008/styles/kendo.default.min.css" rel="stylesheet" />
<script src="http://cdn.kendostatic.com/2014.2.1008/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.2.1008/js/kendo.all.min.js"></script>
<div id="grid"></div>
Found basis for this on JS Bin http://jsbin.com/pifevi/1/edit?html,output
which skips non editable fields
Add a new event handling function:
function onGridKeydown(e) {
if (e.keyCode === kendo.keys.TAB) {
var grid = $(this).closest("[data-role=grid]").data("kendoGrid");
var current = grid.current();
if (!current.hasClass("editable-cell")) {
var nextCell;
if (e.shiftKey) {
nextCell = current.prevAll(".editable-cell");
if (!nextCell[0]) {
//search the next row
var prevRow = current.parent().prev();
var nextCell = prevRow.children(".editable-cell:last");
}
} else {
nextCell = current.nextAll(".editable-cell");
if (!nextCell[0]) {
//search the next row
var nextRow = current.parent().next();
var nextCell = nextRow.children(".editable-cell:first");
}
}
grid.current(nextCell);
grid.editCell(nextCell[0]);
}
});
Then wire up the grid to the event
$("#grid").find("table").on("keydown", onGridKeydown);
You need to add the editable-cell class to each cell so with kendo mvc you would do:
columns.Bound(p => p.foo).HtmlAttributes(new { #class = "editable-cell" }).Title("Foo").Width(120);
And essentially make sure the grid is navigatable
.Navigatable(nav => nav.Enabled(true))

Kendo UI with Javascript Modular Pattern

I'm in the process of creating a big business application using kendo ui. Since application is big. we have started to follow modular patter in javascript code.
When using modular pattern wtih kendo ui. i'm getting some errors.
i have created hierarchy grid. Each grid code will be modular object. like below:
But i'm getting below error: (I have commented error lines like this //error. Please see below)
SCRIPT5007: Unable to get property 'find' of undefined or null reference.
Reason for error is "this" object is referred to window object. But it should refer kendo grid object.. how to resolve this
var Customer = (function ($,window) {
var gridCustomer = null;
var dataSource = null;
var createColumns = function () {
return [
{
field: "FirstName",
title: "First Name",
width: "110px"
},
{
field: "LastName",
title: "Last Name",
width: "110px"
},
{
field: "Country",
width: "110px"
},
{
field: "City",
width: "110px"
},
{
field: "Title"
}
]
};
var setDataSource = function () {
if (customerGridDataSource != undefined) {
return dataSource = new kendo.data.DataSource({
data: customerGridDataSource,
schema: {
data: function (response) {
return response;
},
total: function (response) {
return response.length;
},
model: {
id: "CustomerID",
fields: {
CustomerID: { editable: false, nullable: false, type: "int" },
FirstName: { editable: true, nullable: false, type: "string" },
LastName: { editable: true, nullable: true, type: "string" },
Country: { editable: true, nullable: true, type: "string" },
City: { editable: true, nullable: true, type: "string" },
Title: { editable: true, nullable: true, type: "string" }
}
}
},
pageSize: 5,
serverPaging: false,
serverSorting: false
});
}
else {
alert("Data Source undefined. Please Contact Administrator.")
}
};
var onDataBound = function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());//error
};
var init = function () {
gridCustomer = $("#gridCustomer").kendoGrid({
sortable: true,
filterable: true,
pageable: {
pageSize: 5,
pageSizes: true
},
columns: createColumns(),
dataSource: setDataSource(),
dataBound: onDataBound(),
detailInit: Order.Init()
});
};
return {
Init: function () {
init();
}
}
})(jQuery,window);
var Order = (function ($,window) {
var gridOrder = null;
var dataSource = null;
var createColumns = function () {
return [
{ field: "OrderID", width: "70px" },
{ field: "ShipCountry", title: "Ship Country", width: "110px" },
{ field: "ShipAddress", title: "Ship Address" },
{ field: "ShipName", title: "Ship Name", width: "200px" }
]
};
var setDataSource = function () {
if (customerGridDataSource != undefined) {
return dataSource = new kendo.data.DataSource({
data: customerGridDataSource,
schema: {
data: function (response) {
return response;
},
total: function (response) {
return response.length;
},
model: {
id: "CustomerID",
fields: {
OrderID: { editable: false, nullable: false, type: "int" },
ShipCountry: { editable: true, nullable: false, type: "string" },
ShipAddress: { editable: true, nullable: true, type: "string" },
ShipName: { editable: true, nullable: true, type: "string" }
}
}
},
pageSize: 5,
serverPaging: false,
serverSorting: false,
serverFiltering: false,
filter: { field: "CustomerID", operator: "eq", value: e.data.CustomerID }
});
}
else {
alert("Data Source undefined. Please Contact Administrator.")
}
};
var init = function (e) {
gridOrder = $("<div/>").appendTo(e.detailCell).kendoGrid({
scrollable: false,
sortable: true,
pageable: true,
columns: createColumns(),
dataSource: setDataSource()
});
};
return {
Init: function (e) {
init(e);
}
}
})(jQuery,window);
$(function () {
Customer.Init();
});
Kendo ui provides a parameter called e for dataBound event. e.sender is the grid. So your code should seems to this:
var onDataBound = function (e) {
var grid = e.sender;
grid.expandRow(grid.tbody.find("tr.k-master-row").first());
};
As I mention in comments: It seems the problem is with the dataBound: onDataBound(), because you should set the function onDataBound to the dataBound event not the result of execution onDataBound().The e is undefined because kendo executing the onDataBound() when it wants to set the initial value of dataBound event, not the time the dataBound event has occurred. replace dataBound: onDataBound() with dataBound: onDataBound and try again:
var init = function () {
gridCustomer = $("#gridCustomer").kendoGrid({
sortable: true,
filterable: true,
pageable: {
pageSize: 5,
pageSizes: true
},
columns: createColumns(),
dataSource: setDataSource(),
dataBound: onDataBound, //Not immediately execution
detailInit: Order.Init //Not immediately execution
});
};
You have to remove the parentheses at the end of onDataBound when you add the handler to the grid's configuration object (same with Order.Init), otherwise you're immediately executing the function instead of when the event is triggered:
gridCustomer = $("#gridCustomer").kendoGrid({
sortable: true,
filterable: true,
pageable: {
pageSize: 5,
pageSizes: true
},
columns: createColumns(),
dataSource: setDataSource(),
dataBound: onDataBound,
detailInit: Order.Init
});

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