How to select all checkbox based on custom checkbox in filterTemplate in JsGrid - asp.net-mvc-4

Here i am trying to check all checkbox for using custom checkbox we can see here filterTemplate section and selectAll or unselectAll these are Bold for getting my point
<script>
$(function () {
$.ajax({
type: "GET",
url: "/MerchandiseList/GetMerchant"
}).done(function (data) {
//$("#leftMenu").hide();
//reloadpage(data);
var MyDateField = function (config) {
jsGrid.Field.call(this, config);
};
MyDateField.prototype = new jsGrid.Field({
sorter: function (date1, date2) {
return new Date(date1) - new Date(date2);
},
itemTemplate: function (value) {
if (value == "")
return "";
else {
var date = new Date(value).toDateString()
//var date = new Date(value).toDateString("MM/dd/yyyy")
//return new Date(value).toDateString();
//return value;
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var df = [month, day, year].join('/');
//var df = [year, month, day].join('/');
date = df;
return date;
}
},
insertTemplate: function (value) {
return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() });
},
editTemplate: function (value) {
if (value == "")
return this._editPicker = $("<input>").datepicker({ defaultDate: new Date() });
else {
return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value));
}
},
insertValue: function () {
if (this._insertPicker.datepicker("getDate") != null)
return this._insertPicker.datepicker("getDate"); //.toISOString("MM/dd/yyyy")
//else
// return this._insertPicker.datepicker("getDate");
},
editValue: function () {
//debugger
if (this._editPicker.datepicker("getDate") != null)
//.toISOString("MM/dd/yyyy")
return this._editPicker.datepicker("getDate");
//return this._editPicker.datepicker("getDate").toISOString();
//else
// return this._editPicker.datepicker("getDate");
}
});
jsGrid.fields.myDateField = MyDateField;
$("#jsGrid").jsGrid({
height: "50%",
width: "100%",
filtering: true,
editing: true,
editButtonTooltip: "Edit",
inserting: true,
sorting: true,
paging: true,
autoload: true,
pageButtonCount: 5,
pageSize: 15,
overflow: scroll,
confirmDeleting: true,
deleteConfirm: "Do you really want to delete the merchandise?",
//refreshtext: "Refresh",
//onRefreshed: function (args) { },
selecting: true,
controller: db,
fields: [
{
**filterTemplate**: function (_, item) { // how to get all grid items here? This return only single item but empty in Filter row.
return $("<input>").attr("type", "checkbox")
.prop("checked", $.inArray(item, selectedItems) > -1)
.on("change", function () {
$(this).is(":checked") ? selectAll(item) : unselectAll(item);
});
},
itemTemplate: function (_, item) {
return $("<input>").attr("type", "checkbox")
.prop("checked", $.inArray(item, selectedItems) > -1)
.on("change", function () {
$(this).is(":checked") ? selectItem(item) : unselectItem(item);
});
},
align: "center",
width: 50,
sorting: false,
filtering: false
},
{ type: "control" },
{
name: "Source", type: "text", width: 120, title: "Vendor"
},
{
name: "Description", type: "text", width: 210,
validate: { message: "Description is required!", validator: function (value) { return value != ""; } }
},
{
name: "ModelNumber", type: "text", width: 120, title: "Model#/Item"
},
{ name: "SKU", type: "text", width: 90 },
{ name: "SKU2", type: "text", width: 90 },
{ name: "Comments", type: "text", width: 200 },
{ name: "strReceiveDate", type: "myDateField", width: 80, align: "center", title: "Received" },
{ name: "Location", type: "select", items: data.loc, valueField: "LocationID", textField: "Description", width: 100 },
{ name: "Barcode", width: 80 },
{ name: "BarcodePrinted", type: "checkbox", title: "Barcode Printed", sorting: false },
//{ name: "strLastUpdatedDate", type: "myDateField", width: 80, title: "Last Updated" },
{ name: "strLastUsedDate", type: "myDateField", width: 80, title: "Last Updated" },
{ name: "DamageCode", type: "select", items: data.dam, valueField: "CodeID", textField: "CodeValue", title: "Damage" },
{ name: "strCreatedDate", editable: false, width: 80, title: "Created Date", type: "myDateField" },
{ name: "strShipDate", type: "myDateField", myCustomProperty: "bar", width: 80, title: "Ship Date" },
{ name: "strConsumeDate", type: "myDateField", myCustomProperty: "bar", width: 80, title: "Consume Date" },
{ name: "PendingShipment", type: "checkbox", title: "Pending", sorting: false, width: 60 },
{ name: "Donated", type: "checkbox", title: "Is Donated", sorting: false, width: 60 },
{ name: "ReturnRequested", type: "checkbox", title: "Return Requested", sorting: false },
{ name: "ReturnTo", type: "text", width: 150, title: "Return To" },
{ name: "Quantity", type: "number", width: 50, title: "Qty" },
{ name: "GroupName", type: "text", width: 150, title: "Group Name" },
{ name: "CustomerID", width: 100, title: "Customer ID" }
],
});
var selectedItems = [];
var selectItem = function (item) {
document.getElementById("hdn").value = document.getElementById("hdn").value + "," + item.Barcode;
selectedItems.push(item);
//debugger
var $grid = $("#jsGrid");
$grid.jsGrid("option", "editing", false);
$grid.jsGrid("option", "editing", true);
};
var unselectItem = function (item) {
selectedItems = $.grep(selectedItems, function (i) {
//debugger
return i !== item;
});
var value = document.getElementById("hdn").value;
value = value.replace(item.Barcode, "");
document.getElementById("hdn").value = value;
var $grid = $("#jsGrid");
$grid.jsGrid("option", "editing", false);
$grid.jsGrid("option", "editing", true);
};
var **selectAll** = function (item) {
document.getElementById("hdn").value = document.getElementById("hdn").value + "," + item.Barcode;
selectedItems.push(item);
var $grid = $("#jsGrid");
$grid.jsGrid("option", "editing", false);
$grid.jsGrid("option", "editing", true);
};
var **unselectAll** = function (item) {
selectedItems = $.grep(selectedItems, function (i) {
//debugger
return i !== item;
});
var value = document.getElementById("hdn").value;
value = value.replace(item.Barcode, "");
document.getElementById("hdn").value = value;
var $grid = $("#jsGrid");
$grid.jsGrid("option", "editing", false);
$grid.jsGrid("option", "editing", true);
};
});
});
here the output image here [https://i.stack.imgur.com/gMfwn.png][1]
But noting happens can any one help me

Related

kendo bar chart read never contatct server (cache disabled)

When some external event is triggered I need to refresh chart datasource manually calling:
$(".k-chart").data("kendoChart").dataSource.read();
Everytime I call read, datasource requestEnd is called, but, obiviously no response is available on event handler object.
I can't see any error but the webservice specified in datasource.transport.read.url is never reached after the first request.
Chart load data by server only the first time, here is the configuration:
$scope.chartopts = {
charArea: {
height: 500,
},
title: {
position: "bottom",
text: "A / B"
},
legend: {
position: "top",
visible: true
},
chartArea: {
background: "transparent"
},
seriesDefaults: {
labels: {
visible: true,
background: "transparent",
template: "#= category #: (#= value #)",
align: "alignColumn"
}
},
series: [{
startAngle: 180,
categoryField: 'category',
field: 'value',
padding: 0
}],
dataSource: {
transport: {
read: {
url: wsurl,
type: 'POST',
data: {id: id},
dataType: 'json',
cache: false,
}
},
requestEnd: function(e){
if(e.type == 'read' && e.response){//works only the first time
var rsp = [];
var a = e.response.a;
var b = e.response.b;
var tot = a + b;
if(tot!=0){
var pa = parseFloat(100 * a / tot).toFixed(2);
var pb = parseFloat(100 * b / tot).toFixed(2);
}
else {
pa = 0;
pb = 0;
}
rsp = [{
category: "A",
value: a,
color: "#66FF99",
},{
category: "B",
value: b,
color: "#FF9900",
}];
this.data(rsp);
}
}
},
tooltip: {
visible: true,
},
valueAxis: {
majorGridLines: {
visible: false
},
visible: false
},
categoryAxis: {
majorGridLines: {
visible: false
},
line: {
visible: false
}
}
};
Here is the tag:
<div kendo-chart k-options='chartopts' ></div>
I also tried to call refresh method on chart. Widget on screen is refreshed but datasource remain unchanged.
Solved defining schema property in datasource configuration object and adapting/moving all the logic from requestEnd to schema.parse method.
dataSource: {
transport: {
read: {
url: wsurl,
type: 'POST',
data: {id: id},
dataType: 'json',
cache: false,
}
},
schema: {
data: 'results',
total: 'total',
parse: function(data){
var rsp = [];
var a = data.a;
var b = data.b;
var tot = a + b;
if(tot!=0){
var pa = parseFloat(100 * a / tot).toFixed(2);
var pb = parseFloat(100 * b / tot).toFixed(2);
}
else {
pa = 0;
pb = 0;
}
rsp = {results: [{
category: "A",
value: a,
color: "#66FF99",
},{
category: "B",
value: b,
color: "#FF9900",
}], total: 2};
return rsp;
}
}
}
Everytime I need to run datasource.read(), I also refresh chart:
var chart = $(".k-chart").data("kendoChart");
chart.dataSource.read();
chart.refresh();

Restricting a Rally chart snapshot store to a date period

I want to show some data from Rally using snapshot sotre passed to teh chart like this:
storeConfig: {
find: {
_ItemHierarchy: 15312401235, //PI Object ID
//Release: 9045474054,
_TypeHierarchy: 'HierarchicalRequirement', //Burn on stories
Children: null, //Only include leaf stories,
_ValidTo: { $gte: me._startDateField.value },
_ValidFrom: { $lte: me._endDateField.value }
},
fetch: ['ScheduleState', 'PlanEstimate'],
hydrate: ['ScheduleState'],
sort: {
'_ValidFrom': 1
}
}
The idea is that I want the chart to show only yhe period between Start Date and End Date specified in me._startDateField.value and me._endDateField.value. What is the way of achieving this? Because now the chart displays the data starting from January and not from Start Date.
This example restricts the end date to a selection in the second rallydatepicker instead of defaulting to today's date. See Readme here.
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
launch: function() {
var that = this;
var minDate = new Date(new Date() - 86400000*90); //milliseconds in day = 86400000
var datePicker = Ext.create('Ext.panel.Panel', {
title: 'Choose start and end dates:',
bodyPadding: 10,
renderTo: Ext.getBody(),
layout: 'hbox',
items: [{
xtype: 'rallydatepicker',
itemId: 'from',
minDate: minDate,
handler: function(picker, date) {
that.onStartDateSelected(date);
}
},
{
xtype: 'rallydatepicker',
itemId: 'to',
minDate: minDate,
handler: function(picker, date) {
that.onEndDateSelected(date);
}
}]
});
this.add(datePicker);
var panel = Ext.create('Ext.panel.Panel', {
id:'infoPanel',
componentCls: 'panel'
});
this.add(panel);
},
onStartDateSelected:function(date){
console.log(date);
this._startDate = date;
},
onEndDateSelected:function(date){
this._endDate = date;
console.log(date);
Ext.getCmp('infoPanel').update('showing data between ' + this._startDate + ' and ' + this._endDate);
this.defineCalculator();
this.makeChart();
},
defineCalculator: function(){
var that = this;
Ext.define("MyDefectCalculator", {
extend: "Rally.data.lookback.calculator.TimeSeriesCalculator",
getMetrics: function () {
var metrics = [
{
field: "State",
as: "Open",
display: "column",
f: "filteredCount",
filterField: "State",
filterValues: ["Submitted","Open"]
},
{
field: "State",
as: "Closed",
display: "column",
f: "filteredCount",
filterField: "State",
filterValues: ["Fixed","Closed"]
}
];
return metrics;
}
});
},
makeChart: function(){
if (this.down('#myChart')) {
this.remove('myChart');
}
var timePeriod = new Date(this._endDate - this._startDate);
var project = this.getContext().getProject().ObjectID;
var storeConfig = this.createStoreConfig(project, timePeriod);
this.chartConfig.calculatorConfig.startDate = Rally.util.DateTime.format(new Date(this._startDate), 'Y-m-d');
this.chartConfig.calculatorConfig.endDate = Rally.util.DateTime.format(new Date(this._endDate), 'Y-m-d');
this.chartConfig.storeConfig = storeConfig;
this.add(this.chartConfig);
},
createStoreConfig : function(project, interval ) {
return {
listeners : {
load : function(store,data) {
console.log("data",data.length);
}
},
filters: [
{
property: '_ProjectHierarchy',
operator : 'in',
value : [project]
},
{
property: '_TypeHierarchy',
operator: 'in',
value: ['Defect']
},
{
property: '_ValidFrom',
operator: '>=',
value: interval
}
],
autoLoad : true,
limit: Infinity,
fetch: ['State'],
hydrate: ['State']
};
},
chartConfig: {
xtype: 'rallychart',
itemId : 'myChart',
chartColors: ['Red', 'Green'],
storeConfig: { },
calculatorType: 'MyDefectCalculator',
calculatorConfig: {
},
chartConfig: {
plotOptions: {
column: { stacking: 'normal'}
},
chart: { },
title: { text: 'Open/Closed Defects'},
xAxis: {
tickInterval: 1,
labels: {
formatter: function() {
var d = new Date(this.value);
return ""+(d.getMonth()+1)+"/"+d.getDate();
}
},
title: {
text: 'Date'
}
},
yAxis: [
{
title: {
text: 'Count'
}
}
]
}
}
});

Kendo Change SeriesDefault Chart Type Dynamically

The Code works But I wanna Change Chart Type Dynamically. I tried Change Chart Type in function WeightLine However It does not work. It changes SeriesDefault type , I see new chart type in alert but does not draw new chart type.
var mydata=[{"date":"2013-03-06","data":2916,"name":"weight"},{"date":"2013-03-05","data":3708,"name":"weight"}];
function getFilter(xMin, xMax) {
return [{
field: "date",
operator: "gt",
value: xMin
}, {
field: "date",
operator: "lt",
value: xMax
}];
}
$("#line_chart_weight").kendoChart({
title: {
text: "weight"
},
dataSource:{
data: mydata,
group: {
field: "name"
},
sort: {
field: "date",
dir: "asc"
},
schema: {
model: {
fields: {
date: {
type: "date"
}
}
}
}
},
seriesDefaults: {
type: "scatterLine"
},
series: [{
xField:"date",
yField: "data"
}],
yAxis: {
labels: {
format: "{0}"
},
title: {
text: "KG",
padding: {
left: 20
}}
}, xAxis: {
labels:
{
rotation: -90,
format:"dd-MM-yyyy"
},
title: {
text: "Date",
padding: {
top: 20
}},
type:"date",
name:"CategoryAxis"
},
tooltip: {
visible: true,
format:"dd-MM-yyyy",
color:"white"
},
transitions: false,
drag: onDragw,
zoom: onDragw
});
var weight=$("#line_chart_weight").data("kendoChart");
function onDragw(e) {
var ds = weight.dataSource;
var options = weight.options;
e.originalEvent.preventDefault();
var categoryRange = e.axisRanges.CategoryAxis;
if (categoryRange) {
var xMin = categoryRange.min;
var xMax = categoryRange.max;
options.categoryAxis.min = xMin;
options.categoryAxis.max = xMax;
ds.filter(getFilter(xMin, xMax));
weight.redraw();
}
}
function WeightLine(WeightTypeString){ weight.options.seriesDefaults.type=WeightTypeString;alert(weight.options.seriesDefaults.type); weight.redraw();}
it is a bit weird but i write something to solve this. both of them worked for me. You can modify them for your code.
1.
var chart = $("#chartId").data("kendoChart");
chart.setOptions({ seriesDefaults: {type : "radarColumn"} });
chart.dataSource.read();
chart.refresh();
2.
var chart = $("#chartId").data("kendoChart");
for(i = 0; i< chart.options.series.length;i++){
chart.options.series[i].type = "radarColumn";
}
chart.refresh();

How to bind .Url(Url.Action()) property to toolbar in kendo ui grid(html)

i have a grid developed using kendo ui and asp.net mvc4 razor.in there i have used the html syntax for kendo grid instead of asp.net mvc.
this is the code of my grid
<div id="example" class="k-content">
<div id="batchgrid">
</div>
</div>
<script type="text/javascript" lang="javascript">
$("#batchGrid").click(function () {
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} },
UnitsInStock: { type: "number", validation: { min: 0, required: true} },
Discontinued: { type: "boolean" },
TotalStock: { type: "number" }
}
}
},
// group: {
// field: "UnitPrice", aggregates: [
// { field: "UnitPrice", aggregate: "sum" },
// { field: "TotalStock", aggregate: "sum" }
// ]
// },
aggregate: [{ field: "TotalStock", aggregate: "sum"}]
});
$("#batchgrid").kendoGrid({
dataSource: dataSource,
dataBound: onDataBound,
navigatable: true,
filterable: {
messages: {
and: "And",
or: "Or",
filter: "Apply filter",
clear: "Clear filter",
info: "Filter by"
},
extra: false, //do not show extra filters
operators: { // redefine the string operators
string: {
contains: "Contains",
doesnotcontain: "Doesn't contain",
startswith: "Starts With",
endswith: "Ends"
},
number: {
eq: "Is Equal To",
neq: "Not equal to",
gte: "Greater than or equal to",
lte: "Less than or equal to",
gt: "Greater than",
lt: "Less than"
}
}
},
reorderable: true, //not working
selectable: "multiple",
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50, 100]
},
height: 430,
width: 300,
toolbar: [
{
name: "my-create",
text: "Add new record"
},
{
name: "save",
text: "save changes"
},
{
name: "cancel",
text: "cancel changes"
},
{
name: "export",
text: "Export To Excel"
}
],
columns: [
// { field: "ProductID", title: "No", width: "90px" },
{title: "No", template: "#= ++record #", width: 45 },
{ field: "ProductName", title: "Product Name", width: "350px" },
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" },
{ field: "UnitsInStock", title: "Units In Stock", width: "150px" },
{ field: "Discontinued", title: "Purchase", width: "110px" },
{ field: "TotalStock", title: "Total Stock", width: "150px", footerTemplate: "Total : #= kendo.toString(sum, 'C') #", format: "{0:c2}" }
//{ command: ["destroy"], title: " ", width: "175px" }
],
export: {
cssClass: "k-grid-export-image",
title: "people",
createUrl: "/Home/ExportToExcel",
downloadUrl: "/Home/GetExcelFile"
},
groupable: {
messages: {
empty: "Drop columns here"
}
}, //not working
columnMenu: {
sortable: true,
filterable: true,
messages: {
columns: "Hide/Show Columns",
filter: "Apply filter",
sortAscending: "Sort (asc)",
sortDescending: "Sort (desc)"
}
},
resizable: true,
dataBinding: function () {
record = (this.dataSource.page() - 1) * this.dataSource.pageSize();
},
sortable: {
mode: "multiple"
},
sort: { field: "ProductID", dir: "asc" },
editable: { mode: "incell", createAt: "bottom" }
});
//custom global variables
newRowAdded = false;
checkedOnce = false;
var grid = $("#batchgrid").data("kendoGrid");
$(".k-grid-my-create", grid.element).on("click", function (e) {
window.newRowAdded = true;
var dataSource = grid.dataSource;
var total = dataSource.data().length;
dataSource.insert(total, {});
dataSource.page(dataSource.totalPages());
grid.editRow(grid.tbody.children().last());
});
grid.bind("saveChanges", function () {
window.newRowAdded = false;
// var grid = $("#batchgrid").data("kendoGrid");
// grid.dataSource.sort({ field: "ProductID", dir: "asc" });
// GetValOf();
// var grid = $('#batchgrid').data("kendoGrid");
// var total = 0;
// $.each(grid.dataSource.view(), function () {
// total += this.TotalStock;
// });
// alert(total);
});
grid.bind("cancelChanges", function () {
window.newRowAdded = false;
});
$(".k-grid-export", "#batchgrid").bind("click", function (ev) {
// your code
// alert("Hello");
var grid = $("#batchgrid").data("kendoGrid");
grid.dataSource.pageSize(parseInt($("#batchgrid").data("kendoGrid").dataSource.data().length));
excelImport();
});
});
</script>
but i got some example code for importing grid data to excel and in there they used asp.net mvc syntax.
here is the code.
#(
Html.Kendo().Grid(Model).Name("Grid")
.DataSource(ds => ds.Ajax()
.Model(m =>
{
m.Id(p=>p.ProductID);
})
.Read(r => r.Action("Read", "Home"))
)
.ToolBar(toolBar =>
toolBar.Custom()
.Text("Export To Excel")
.HtmlAttributes(new { id = "export" })
.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
)
.Columns(columns =>
{
columns.Bound(p => p.ProductID);
columns.Bound(p => p.ProductName);
columns.Bound(p => p.UnitPrice).Format("{0:c}");
columns.Bound(p => p.QuantityPerUnit);
})
.Events(ev => ev.DataBound("onDataBound"))
.Pageable()
.Sortable()
.Filterable()
)
but my problem is i need to add below line of code to my grid(in first code mentioned above).
.ToolBar(toolBar =>
toolBar.Custom()
.Text("Export To Excel")
.HtmlAttributes(new { id = "export" })
.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
)
but im stucked with this single line
.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
can somebody please tell me that how to use this code in my html grid..
Write Toolbar manual
<div class="k-toolbar k-grid-toolbar k-grid-top">
<a class="k-button k-button-icontext " id="exportCsv" href="/Home/ExportToCsv?take=50&skip=0&page=1&pageSize=10&filter=~&sort=" id="exportToCSV"><span></span>Export CSV</a>
<a class="k-button k-button-icontext " id="exportXls" href="/Home/ExportToXls?take=50&skip=0&pageSize=10&filter=~&sort=" id="exportToExcel"><span></span>Export Excel</a>
</div>
then add databound to kendoGrid
....
editable: false, // enable editing
sortable: true,
filterable: true,
scrollable: false,
dataBound: onDataBound,
columns: [.....
then write 'onDataBound' function
<script>
function onDataBound(e) {
var grid = $('#grid').data('kendoGrid');
var take = grid.dataSource.take();
var skip = grid.dataSource.skip();
var page = grid.dataSource.page();
var sort = grid.dataSource.sort();
var pageSize = grid.dataSource.pageSize();
var filter = JSON.stringify(grid.dataSource.filter());
// Get the export link as jQuery object
var $exportLink = $('#exportXls');
// Get its 'href' attribute - the URL where it would navigate to
var href = $exportLink.attr('href');
// Update the 'take' parameter with the grid's current page
href = href.replace(/take=([^&]*)/, 'take=' + take || '~');
// Update the 'skip' parameter with the grid's current page
href = href.replace(/skip=([^&]*)/, 'skip=' + skip || '~');
// Update the 'page' parameter with the grid's current page
href = href.replace(/page=([^&]*)/, 'page=' + page || '~');
// Update the 'sort' parameter with the grid's current sort descriptor
href = href.replace(/sort=([^&]*)/, 'sort=' + sort || '~');
// Update the 'pageSize' parameter with the grid's current pageSize
href = href.replace(/pageSize=([^&]*)/, 'pageSize=' + pageSize);
//update filter descriptor with the filters applied
href = href.replace(/filter=([^&]*)/, 'filter=' + (filter || '~'));
// Update the 'href' attribute
$exportLink.attr('href', href);
$('#exportCsv').attr('href', href.replace('ExportToXls', 'ExportToCsv'));
}
</script>
And this is the Action, and parameters
public FileResult ExportToXls(int take, int skip, IEnumerable<Sort> sort, string filter)
{
try
{
Filter objfilter = JsonConvert.DeserializeObject<Filter>(filter);
var lstContactFormData = XmlData.GetIletisimBilgileri().OrderByDescending(i => i.tarih);
//Get the data representing the current grid state - page, sort and filter
//IEnumerable products = _db.Products.ToDataSourceResult(request).Data;
IEnumerable contactsDatas = lstContactFormData.AsQueryable().ToDataSourceResult(take, skip, sort, objfilter).Data;
...
...

Finding the row id in a gridpanel

How do I find the row index in a gridpanel that has comboboxes in on of the columns and is used to update the store/database through and ajax proxy? I'm using Ext.grid.plugin.CellEditing. Here's my code. Thanks for looking at it!
Ext.Loader.setConfig({
enabled: true
});
Ext.Loader.setPath('Ext.ux', '/extjs4/examples/ux');
Ext.require([
'Ext.layout.container.Fit',
'Ext.grid.*',
'Ext.data.*',
'Ext.util.*',
'Ext.panel.*',
'Ext.selection.CellModel',
'Ext.state.*',
'Ext.form.*',
'Ext.ux.CheckColumn'
]);
Ext.define('Ext.app.HirePlanGrid', {
extend: 'Ext.panel.Panel',
alias: 'widget.hirePlangrid'
,hireplanstoreId: 'hireplanstore'
,hiremonthstoreId: 'hiremonthstore'
,renderMonth : function (value, p, record) {
var fkStore = Ext.getStore(this.up('hirePlangrid').hiremonthstoreId);
var rec = fkStore.findRecord("MONTH_ID", value);
//return rec.get("ABBREVIATED_MONTH");
}
,initComponent: function() {
this.editing = Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 2
});
var objMonthStore = Ext.getStore(this.hiremonthstoreId);
objMonthStore.load();
var objStore = Ext.getStore(this.hireplanstoreId);
objStore.setProxy( {
type: 'ajax',
url: 'hireplan.cfc?method=getEmployees'
});
objStore.load();
var onDeleteClick = function(field, value, options) {
// var objPanel = this.down('gridpanel');
var selection = Ext.getCmp('grid').getSelectionModel().getSelection();
alert(selection);
// var selection = getView().getSelectionModel().getSelection()[r];
if (value) {
alert(value);
objStore.remove(value);
objStore.sync();
}
};
var onUpdateClick = function(field, value, options) {
alert('field= ' + field + ' value= '+ value+ 'options= '+ options);
objStore.update(objStore.getAt(value));
onSync();
};
Ext.apply(this, {
layout: 'fit',
width: 800,
//height: 1500,
items: [{
xtype: 'grid',
id : 'gridgrid',
//height: 300,
store: objStore,
selModel: { selType: 'cellmodel' },
selType : 'rowmodel',
plugins: [this.editing],
// plugins: [cellEditing],
columnLines: true,
viewConfig: {stripeRows: true},
//loadMask: true,
disableSelection: true,
listeners: {
selectionchange: function(selModel, selected) {
var selection = Ext.getCmp('gridgrid').getSelectionModel().getSelection();
}
},
columns: [
{ header: 'rowid', hidden: true, dataIndex: 'ROWID'},
{
header: 'Indicator',
id: 'chkcolumn',
xtype: 'checkcolumn',
dataIndex: 'CHK_COL',
editor: {
xtype: 'checkbox',
cls: 'x-grid-checkheader-editor'
},
listeners : checkchange : function(column, recordIndex, checked)
{
alert('checked rindex= ' + recordIndex);
onDeleteClick(column, recordIndex, checked);
//or send a request
}
}
},
{
id: 'employeeid',
header: 'employeeid',
width: 80,
hidden: false,
sortable: true,
dataIndex: 'EMPLOYEEID',
flex: 1
},
{
id: 'NATIONALIDNUMBER',
header: 'NATIONALIDNUMBER',
width: 80,
sortable: true,
dataIndex: 'NATIONALIDNUMBER',
flex: 1
},
{
id: 'MARITALSTATUS',
header: 'MARITALSTATUS',
width: 80,
sortable: true,
dataIndex: 'MARITALSTATUS',
flex: 1
},
{
id: 'PotentialforInsourcingKV',
header: 'Potential for Insourcing',
width: 30,
sortable: true,
dataIndex: 'POTENTIAL_FOR_INSOURCING',
flex: 1,
editor: {
id: 'thiscombo',
xtype: 'combobox',
typeAhead: true,
triggerAction: 'all',
selectOnTab: true,
store: [
['1', 'Yes'],
['0', 'No']
],
lazyRender: true,
listClass: 'x-combo-list-small',
listeners: { 'select' : function(r){
var selval = Ext.getCmp("thiscombo").getValue();
//var recval = Ext.getCmp("grid").getValue();
//var selection = getView().getSelectionModel().getSelection()[r]
alert(selval + ' ' + rowIdx);
// onUpdateClick(editor, rowIdx, value );
}
},
}
},
{
id: 'ABBREVIATED_MONTH',
header: 'ABBREVIATED_MONTH',
width: 80,
sortable: true,
dataIndex: 'ABBREVIATED_MONTH',
flex: 1,
renderer: this.renderMonth,
field: {
xtype: 'combobox',
store: Ext.getStore(this.hiremonthstoreId),
typeAhead: true,
lazyRender: true,
queryMode: 'local',
displayField: 'ABBREVIATED_MONTH',
valueField: 'MONTH_ID',
listClass: 'x-combo-list-small'
}
},
{
id: 'SALARIEDFLAG',
header: 'SALARIEDFLAG',
width: 80,
sortable: true,
dataIndex: 'SALARIEDFLAG',
flex: 1
}],
features: [{
ftype: 'rowbody'
}]
}]
});
this.callParent(arguments);
//this.getSelectionModel().on('selectionchange', this.onSelectChange, this);
}, //initComponent
getSelectedRowIndex : function(){
var r, s;
r = this.getView().getSelectionModel().getSelection();
s = this.getStore();
return s.indexOf(r[0]);
},
onSelectChange: function(selModel, selections){
this.down('#delete').setDisabled(selections.length === 0);
},
onSync: function() {
objStore.sync();
},
viewConfig: {},
});
I read in another post that what I needed to do was add a listener to this.cellediting and use the 'beforeedit' event to find the row index, and then set to variables:
var rIdx = '';
var cIdx = '';
this.cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1,
listeners: {
'beforeedit': function(e){
var me = this;
var allowed = !!me.isEditAllowed;
if (!me.isEditAllowed)
Ext.Msg.confirm('confirm', 'Are you sure you want edit?', function(btn){
if (btn !== 'yes')
return;
me.isEditAllowed = true;
me.startEditByPosition({
row: e.rowIdx,
column: e.colIdx
});
});
rIdx = e.rowIdx;
cIdx = e.colIdx;
alert('rIdx= ' + rIdx + ' cIdx = ' + cIdx);
return allowed;
},
'edit': function(e){
this.isEditAllowed = true;
}
}
});