Requirement How to excel export hidden fields using kendoui grid
By using kendo editor i have implemented grid and i want to export hidden field using Excel export in kendo ui Grid Here I want to export Id field in Excel which is hidden here
My main moto is to export the hidden columns using excel export
<div id='grid-container'>
<div id='student-details-grid'
data-role='grid'
data-groupable='true'
data-sortable='true'
data-toolbar=['excel']
data-excel="{fileName: 'StudentDetails.xlsx', proxyURL: '/save', filterable: true, allPages: true}"
data-height='450px'
data-pageable="[
{'refresh':'true' },
{ 'pageSizes':'true'},
{'buttonCount':'5'}
]"
data-bind='source:gridDataSource'
data-columns="[{'field':'Id','title':'Id'},{'field':'Name','title':'Name'},{'field':'FatherName','title':'FatherName'},{'field':'Email','title':'Email'},{'field':'Address','title':'Address'},{'field':'ContactNo','title':'ContactNo'}]"
style="height: 550px">
</div>
</div>
<script type="text/javascript">
var viewModel = '';
$(document).ready(function (e) {
viewModel = kendo.observable({
gridDataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/Home/GetStudents",
dataType: "json"
}
},
pageSize: 10,
schema: {
model: {
id: "Id",
fields: {
Id: { editable: false, nullable: true },
Name: { validation: { required: true } },
FatherName: { type: "text", validation: { required: true, min: 1 } },
Email: { type: 'email', validation: { min: 0, required: true } },
Address: { type: "text", validation: { min: 0, required: true } },
ContactNo: { type: 'text', validation: { min: 0, required: true } },
}
},
parse: function (data) {
debugger
if (!data.success && typeof data.success !== 'undefined') {
gridDataSource.read();
}
if (data.success) {
viewModel.gridDataSource.read();
}
return data;
}
}
}),
});
kendo.bind($("#grid-container"), viewModel);
});
</script>
*Global variable
isExport = false;
data-bind="source: dataSource,events:{excelExport : onExcelExport}"
onExcelExport: function (e) {
var sheet = e.workbook.sheets[0];
for (var rowIndex = 1; rowIndex < sheet.rows.length; rowIndex++) {
var row = sheet.rows[rowIndex];
for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
if (cellIndex === 6 || cellIndex === 8 || cellIndex === 20)
row.cells[cellIndex].format = "HH:mm"
}
}
var gridcolumn = e.sender.columns;
if (!isExport) {
$.each(gridcolumn, function (index, value) {
if (value.hidden)
e.sender.showColumn(index);
else if (value.hidden === false)
e.sender.hideColumn(index);
e.sender.hideColumn(0);
});
e.preventDefault();
isExport = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
$.each(gridcolumn, function (index, value) {
if (value.hidden === false)
e.sender.hideColumn(index);
else
e.sender.showColumn(index);
});
isExport = false;
}
},
Related
I use kendoDropDownList and have the following code:
<div id="memberNotInit-grid"></div>
<script>
$(document).ready(function () {
$("#memberNotInit-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("MemberNotInitList", "RandomPoolInit"))",
type: "POST",
dataType: "json",
data: function() {
var data = {
};
addAntiForgeryToken(data);
return data;
}
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: #(Model.PageSize),
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
pageSizes: [#(Model.AvailablePageSizes)],
#await Html.PartialAsync("_GridPagerMessages")
},
editable: {
confirmation: "#T("Common.DeleteConfirmation")",
mode: "inline"
},
scrollable: false,
columns: [
{
field: "FirstName",
title: "#T("PoolMemberList.Fields.FirstName")",
width: 150
},
{
field: "LastName",
title: "#T("PoolMemberList.Fields.LastName")",
width: 150
},
{
field: "Status",
template: columnTemplateFunction
},
{
field: "Reason",
width: 150,
template: "<input data-bind='value:Reason' class='reasonTemplate' />",
//hidden: true
}
],
dataBound: function (e) {
var grid = e.sender;
var items = e.sender.items();
items.each(function (e) {
var dataItem = grid.dataItem(this);
var ddt = $(this).find('.dropDownTemplate');
$(ddt).kendoDropDownList({
value: dataItem.value,
dataSource: ddlDataSource,
dataTextField: "displayValue",
dataValueField: "Status",
change: onDDLChange
});
var reason = $(this).find('.reasonTemplate');
$(reason).keydown(reasonChange);
reason.hide();
});
}
});
var ddlDataSource = [
{
Status: #((int)DriverRandomPoolStatus.Enrollment),
displayValue: "Enrollment"
},
{
Status: #((int)DriverRandomPoolStatus.Active),
displayValue: "Active"
},
{
Status: #((int)DriverRandomPoolStatus.Excused),
displayValue: "Excused"
}
];
function columnTemplateFunction(dataItem) {
var input = '<input class="dropDownTemplate"/>'
return input
};
function onDDLChange(e) {
var element = e.sender.element;
var row = element.closest("tr");
var grid = $("#memberNotInit-grid").data("kendoGrid");
var dataItem = grid.dataItem(row);
dataItem.set("Status", e.sender.value());
//alert(e.sender.value());
if (dataItem.Status == #((int)DriverRandomPoolStatus.Active)) {
$.ajax({
method: "POST",
url: "#Html.Raw(Url.Action("ChangeMemberStatus", "RandomPoolInit"))",
data: { id: dataItem.Id, status: dataItem.Status }
}).done(function () {
grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").hide();
grid.pager.refresh();
});
}
if (dataItem.Status == #((int)DriverRandomPoolStatus.Excused)) {
grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").find('.reasonTemplate').show();
var ddl = grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").find('.dropDownTemplate');
//ddl.value(dataItem.Status);
}
};
function reasonChange(event) {
if (event.keyCode === 13) {
var element = event.target;
var row = element.closest("tr");
var grid = $("#memberNotInit-grid").data("kendoGrid");
var dataItem = grid.dataItem(row);
var r = grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").find('.reasonTemplate').val();
$.ajax({
method: "POST",
url: "#Html.Raw(Url.Action("ChangeMemberStatus", "RandomPoolInit"))",
data: { id: dataItem.Id, status: dataItem.Status, reason: r }
}).done(function () {
grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").hide();
grid.pager.refresh();
});
}
}
});
</script>
but when we select "Exclused" from dropdownlist value of dropdownlist is dumped to Enrollment (first value from dropdownlist). Why so and how to fix it?
I fixed it the following way:
$(ddt).kendoDropDownList({
value: dataItem.Status,
.....
});
not:
value: dataItem.value,
Below is a sample of integrating multiselect with kendo ui filter row.
http://dojo.telerik.com/eriMA
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
autoBind:true,
columns: [
{
field: "color",
filterable: {
cell: {
template: function (args) {
// create a MultiselectList of unique values (colors)
args.element.kendoMultiSelect({
dataSource: args.dataSource,
dataTextField: "color",
dataValueField: "color",
valuePrimitive: true,
// tagMode: true
});
},
showOperators: false
}
}
},
{ field: "age" } ],
filterable: { mode: "row" },
dataSource: { data: [ { color: "#ff0000", age: 30 }, { color: "#000000", age: 33 }], requestStart: onRequestStart }});
function onRequestStart(e){
var filter = e.sender.filter();
if (filter && filter.filters && filter.filters.length > 0) {
var filter1 = filter.filters;
for (var i = 0; i < filter1.length; i++) {
if (filter1[i].field == "color" && filter1[i].value) {
var colorList = filter1[i].value.split(",");
if (colorList.length > 0) {
var newFilter = { logic: "or", filters: [] };
for (var k = 0; k < colorList.length; k++) {
newFilter.filters.push({ field: "color", operator: "eq", value: colorList[k] });
}
filter1 = filter1.splice(i, 1, newFilter);
e.preventDefault();
e.sender.filter(filter);
}
}
}
}
}
</script>
Now, I want to set a default filter for the grid. For that I have created another sample.
http://dojo.telerik.com/eriMA/2
But unfortunately, if the grid dataSource data is initially empty, the multiselect value gets reset with first value. However, the data is filtered correctly. Can somebody help to overcome this limitation.
I have identified that somehow the filter cell get cleared after the dataBound event, if the dataSource is emtpy. So I set the value back using a timeout.
here is the link to updated source. http://dojo.telerik.com/eriMA/7
<div id="grid"></div>
<script>
var colorMulti = null;
var grid = $("#grid").kendoGrid({
autoBind:false,
columns: [
{
field: "ShipCity",
filterable: {
cell: {
template: function (args) {
// create a MultiselectList of unique values (colors)
colorMulti =args.element.kendoMultiSelect({
dataSource: {data : ["Lyon","Graz","Bern"]},
valuePrimitive: true,
// tagMode: true
}).data("kendoMultiSelect");
},
showOperators: false
}
}
},
{ field: "OrderID" } ],
filterable: { mode: "row" },
dataSource: {
type: "odata",
transport: {
read: "//demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 20,
requestStart:onRequestStart
},
dataBound: onDataBound
}).data("kendoGrid");
function onRequestStart(e){
var filter = e.sender.filter();
if (filter && filter.filters && filter.filters.length > 0) {
var filter1 = filter.filters;
for (var i = 0; i < filter1.length; i++) {
if (filter1[i].field == "ShipCity" && filter1[i].value) {
var colorList = filter1[i].value.split(",");
if (colorList.length > 0) {
var newFilter = { logic: "or", filters: [] };
for (var k = 0; k < colorList.length; k++) {
newFilter.filters.push({ field: "ShipCity", operator: "eq", value: colorList[k] });
}
filter1 = filter1.splice(i, 1, newFilter);
e.preventDefault();
e.sender.filter(filter);
}
}
}
}
}
function onDataBound(e){
var multiSelectValue = [];
var filter = grid.dataSource.filter();
if (filter && filter.filters && filter.filters.length > 0) {
var filter1 = filter.filters;
for (var i = 0; i < filter1.length; i++) {
if (filter1[i].field == "ShipCity" && filter1[i].value) {
multiSelectValue.push(filter1[i].value);
} else if (filter1[i].filters && filter1[i].filters.length > 0 && filter1[i].logic == "or") {
var filter2 = filter1[i].filters;
var multiSelectValue = [];
for (var j = 0; j < filter2.length; j++) {
if (filter2[j].field == "ShipCity") {
multiSelectValue.push(filter2[j].value);
}
}
}
}
}
setTimeout(function () { colorMulti.value(multiSelectValue) });
}
$(document).ready(function () {
grid.dataSource.filter({ "filters": [{ "operator": "eq", "value": "Lyon,Graz,Bern", "field": "ShipCity" }], "logic": "and" });
});
</script>
http://jsfiddle.net/bhoff/ZCyPx/50/
$("#grid").kendoGrid({
dataSource:{
data:entries,
schema:{
parse:function (response) {
$.each(response, function (idx, elem) {
if (elem.time && typeof elem.time === "string") {
elem.time = kendo.parseDate(elem.time, "HH:mm:ss");
}
if (elem.datetime && typeof elem.datetime === "string") {
elem.datetime = kendo.parseDate(elem.datetime, "HH:mm:ss");
}
});
return response;
}
}
},
columns:[
{ command: [ "edit" ] },
{ field:"type", title:"Cash Transation Type" },
{ field:"begintime", title:"Begin Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
{ field:"endtime", title:"End Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
],
editable:"inline",
navigatable:true
});
Based on my example how do I stop the user from editing my "Cash Transation Type" column?
Does it have something to do with this -> editable:"inline" ?
look here
you need to set in the datasource
<script>
var dataSource = new kendo.data.DataSource({
schema: {
model: {
id: "ProductID",
fields: {
ProductID: {
//this field will not be editable (default value is true)
editable: false,
// a defaultValue will not be assigned (default value is false)
nullable: true
},
ProductName: {
//set validation rules
validation: { required: true }
},
UnitPrice: {
//data type of the field {Number|String|Boolean|Date} default is String
type: "number",
// used when new model is created
defaultValue: 42,
validation: { required: true, min: 1 }
}
}
}
}
});
</script>
You would normally set this on your DataSource on the schema.model.fields.
var data = new kendo.data.DataSource({
schema: {
model: {
fields: {
type: { editable: "false" }
Add editable in the field you do not want to enable Edit,
columns:[
{ command: [ "edit" ] },
{ field:"type", title:"Cash Transation Type", editable: false },
{ field:"begintime", title:"Begin Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
{ field:"endtime", title:"End Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
],
editable:"inline",
navigatable:true
});
I need help about a kendo grid,
I call a webservice to fill a datasource of the grid. It seems to work fine, but the data are not displayed in the grid.
The webservice call returns 7 records, and in the grid there are 7 rows, but they are empty.
this is the code:
var mime_charset = "application/json; charset=utf-8";
var serverSelectReturnsJSONString = true;
var model_definition = {
id: "ID",
fields: {
customer_id: { type: "number" },
name_customer: { type: "string" },
address_customer: { type: "string" }
}
}
$(document).ready(function () {
var ds = createJSONDataSource();
$("#grid").kendoGrid({
selectable: true,
theme: "metro",
dataSource: ds,
scrollable: true,
pageable: true,
// height: 300,
toolbar: ["save", "cancel"],
columns: ["ID", "Nome", "Indirizzo"],
editable: true
});
ds.read();
});
and this is the function for filling the datasource:
function createJSONDataSource() {
var dataSource = new kendo.data.DataSource({
severFiltering: true,
serverPaging: true,
PageSize: 15,
//batch: true,
transport: {
autoSync: true,
read: {
type: "POST",
url: "WebServices/GetDataTest.asmx/getCustList",
dataType: "json",
contentType: mime_charset
}
},
schema: {
data: function (data) {
if (data) {
if (serverSelectReturnsJSONString)
return $.parseJSON(data.d);
else
return data.d;
}
},
total: function (result) {
if (!result) return 0;
var xxx = result.d;
if (xxx == null) {
return result.length || 0;
}
if (result.d) {
if (serverSelectReturnsJSONString) {
var data = $.parseJSON(result.d);
return data.length || 0;
}
else {
return result.d.TotalRecords || result.d.length || result.length || 0;
}
}
},
model: model_definition
}
});
dataSource.options.schema.parse = function (dataJ) {
var data;
data = $.parseJSON(dataJ.d);
if (data) {
$.each(data, function (i, val) {
$.each(model_definition.fields, function (j, col) {
if (col.type == "date" || col.type == "datetime") {
val[j] = toDate(val[j]);
}
})
});
var ret = { d: JSON.stringify(data) };
return ret;
}
}
dataSource.reader.parse = dataSource.options.schema.parse;
return dataSource;
}
Your columns definition is not correct, it is an array but of objects (not strings). Check documentation here. If should be something like:
columns: [
{ field: "ID" },
{ field: "Nome" },
{ field: " "Indirizzo" }
],
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!");
});