rowdata is undefined - javascript

I am struggling to see where I am getting an error of 'rowdata is undefined'? when I run my script and press the delete button. I am using jqxwidgets grid:
http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/index.htm
If someone could help out new user or how I can troubleshoot in firebug 1.9, I would be grateful. I have included my code for your inspection. Thank you.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
<link rel="stylesheet" href="../../jqwidgets/styles/jqx.classic.css" type="text/css" />
<script type="text/javascript" src="../../scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqx-all.js"></script>
<script type="text/javascript" src="../../scripts/gettheme.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxdatetimeinput.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcalendar.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxtooltip.js"></script>
<script type="text/javascript" src="../../jqwidgets/globalization/jquery.global.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// prepare the data
var source =
{
datatype: "json",
datafields: [
{ name: 'id'},
{ name: 'type'},
{ name: 'service'},
{ name: 'quantity'},
{ name: 'department'},
{ name: 'date', type: 'date', format: 'yyyy-MM-dd HH:mm:ss'},
],
url: 'data.php',
updaterow: function (rowid, rowdata) {
// synchronize with the server - send update command
var data = "update=true&type=" + rowdata.type + "&service=" + rowdata.service + "&quantity=" + rowdata.quantity;
data = data + "&department=" + rowdata.department + "&date=" + rowdata.date;
data = data + "&id=" + rowdata.id;
$.ajax({
dataType: 'json',
url: 'data.php',
data: data,
success: function (data, status, xhr) {
// update command is executed.
//alert(rowdata);
}
});
},
deleterow: function (rowid, rowdata) {
// synchronize with the server - send update command
var data = "delete=true&type=" + rowdata.type + "&service=" + rowdata.service + "&quantity=" + rowdata.quantity;
data = data + "&department=" + rowdata.department + "&date=" + rowdata.date;
data = data + "&id=" + rowdata.id;
$.ajax({
dataType: 'json',
url: 'data.php',
data: data,
success: function (data, status, xhr) {
// update command is executed.
//alert(rowid);
console.log(rowid);
}
});
}
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
source: source,
theme: 'classic',
width: 900,
altrows: true,
pageable: true,
sortable: true,
filterable: true,
autoheight: true,
pagesizeoptions: ['10', '20', '30', '40'],
editable: true,
ready: function () {
var button = $("<input type='button' value='Add' id='myButton'/>");
button.jqxButton({ height: 20 });
button.click(function () {
$("#jqxgrid").jqxGrid('addrow', null, []);
});
$(".jqx-grid-pager > div:first").append(button);
},
ready: function () {
//var value = $('#jqxrid').jqxGrid('deleterow', rowid);
var delbutton = $("<input type='button' value='Delete' id='DelButton'/>");
delbutton.jqxButton({ height: 20 });
delbutton.click(function () {
$('#jqxgrid').jqxGrid('deleterow', id);
});
$(".jqx-grid-pager > div:first").append(delbutton);
},
columns: [
{ text: 'id', editable: false, datafield: 'id', width: 100 },
{ text: 'Type', datafield: 'type', width: 150},
{ text: 'Service', datafield: 'service', width: 150 },
{ text: 'Quantity', datafield: 'quantity', width: 180 },
{ text: 'Department', datafield: 'department', width: 90 },
{ text: 'Date', datafield: 'date', columntype: 'datetimeinput', cellsformat: 'dd/MM/yyyy HH:mm:ss', width: 230, showCalendarButton: false }
]
});
});
</script>
</head>
<body class='default'>
<div id='content'>
<script type="text/javascript">
$(document).ready(function () {
var theme = 'classic';
// Create a jqxDateTimeInput
$("#jqxWidget").jqxDateTimeInput({ width: '250px', height: '25px', theme: theme, formatString: 'dd/MM/yyyy HH:mm:ss' });
});
</script>
<div id='jqxWidget'>
</div>
</div>
<div id="jqxgrid"></div>
</body>
</html>

You are invoking deleterow() without the proper parameters :)
Signature:
deleterow: function (rowid, rowdata) {}
Invocation:
delbutton.click(function () {
$('#jqxgrid').jqxGrid('deleterow', id /* Missing argument */ );
});
You should add the rowdata as an argument. I don't think this code is to be considered very safe.. (which could be rewritten anyways, skipping the "data = data +", see below ).
var data = "delete=true&type=" + rowdata.type + "&service=" + rowdata.service + "&quantity=" + rowdata.quantity;
data = data + "&department=" + rowdata.department + "&date=" + rowdata.date;
data = data + "&id=" + rowdata.id;
You can obtain the rows as follows (
You should ask for a confirmation, first! ):
delbutton.click(function () {
var rows = $('#grid').jqxGrid('getrows'),
selectedRowIndex = $('#grid').jqxGrid('getselectedrowindex'),
selectedRow = rows[ selectedRowIndex ];
if( confirm("Are you sure you wish to delete the row with index '" + selectedRowIndex + "'?") {
$('#jqxgrid').jqxGrid('deleterow', selectedRowIndex, selectedRow );
}
});
This would be more readable and usable:
var data = [
"delete=", "true",
"&type=", rowdata.type,
"&service=", rowdata.service,
"&quantity=", rowdata.quantity,
"&department=", rowdata.department,
"&date=", rowdata.date,
"&id=", rowdata.id
].join("");
Actually I think the following might make it more complex and less errorprone, but easier to use:
// Another solution
var customDataProperties = {
"delete": "true"
// ,"another": 2
}
var rowdataProperties = [
"type",
"service",
"quantity",
"department",
"date",
"id"
];
function getData( rowdataObject ) {
// Add additional
var data = [];
function createParameterSetString( property, value ) {
return [ "&", property, "=", value ].join("");
}
for( var propertyName in customDataProperties ) {
data.push( createParameterSetString( propertyName, customDataProperties[ propertyName ] ) );
}
for( var i = 0, ln = rowdataProperties.length; i < ln; i++ ) {
var property = rowdataProperties[i];
data.push( createParameterSetString( property, rowdataObject[ property ] ) );
}
if( data.length != 0 ) { data.pop( 0 ); }
return data.join("");
}
As you can see, you can easily extend parameters this way.

Related

JsGrid Sorting Not working on Customized column

The sorting function will no longer work on column that is using itemTemplate and headerTemplate.
You can see a fiddle from here.
As you can see, in the column "Client ID", the sorting works really well. But on column "Client Name", the sorting doesn't work as I am using itemTemplate and headerTemplate for customization.
Any workaround is really appreciated.
Here's the code:
$("#jsGrid").jsGrid({
width: "100%",
sorting: true,
paging: true,
data: [{
ClientId: 1,
Client: "Aaaa Joseph"
},
{
ClientId: 2,
Client: "Zzzz Brad"
},
{
ClientId: 3,
Client: "Mr Nice Guy"
}
],
fields: [{
width: 80,
name: "ClientId",
type: "text",
title: "Client ID"
},
{
width: 80,
itemTemplate: function(value, item) {
return "<div>" + item.Client + "</div>";
},
headerTemplate: function() {
return "<th class='jsgrid-header-cell'>Client Name</th>";
}
},
]
});
In jsgrid name is a property of data item associated with the column. And on header click this _sortData function will call in jsgrid.js for sorting data. And this name config will use here. So for this you have to provide this config other it will blank and no data sorting on header click.
Please search this below function in jsgrid.js
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if (sortField) {
this.data.sort(function(item1, item2) {
return sortFactor * sortField.sortingFunc(item1[sortField.name], item2[sortField.name]);
});
}
},
In above code sortField.name as column config and it is must mandatory.
DEMO
$("#jsGrid").jsGrid({
width: "100%",
sorting: true,
paging: true,
data: [
{ ClientId : 1, Client: "Aaaa Joseph"},
{ ClientId : 2, Client: "Zzzz Brad"},
{ ClientId : 3, Client: "Mr Nice Guy"}
],
fields: [
{
width: 80,
name: "ClientId",
type: "text",
title: "Client ID"
},
{
width: 80,
name:'Client',
itemTemplate: function (value, item) {
return "<div>"+item.Client+"</div>";
},
headerTemplate: function () {
return "<th class='jsgrid-header-cell'>Client Name</th>";
}
},
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<div id="jsGrid"></div>
Another way you can make manually sorting on header click.
Way to sort JS grid on column after grid load :
onRefreshing: function (args) {
fundCodeList = [];
jsonNumLst = [];
jsonNANLst = [];
if(this._visibleFieldIndex(this._sortField) == -1
|| this._visibleFieldIndex(this._sortField)==1){
$.each(filteredData, function(inx, obj) {
if($.isNumeric(obj.fundCode)){
jsonNumLst.push(obj);
}else{
jsonNANLst.push(obj);
}
});
if(this._sortOrder == undefined || this._sortOrder == 'asc'){
jsonNumLst.sort(sortByNumFCAsc);
jsonNANLst.sort(sortByNANFCAsc);
}else if(this._sortOrder == 'desc'){
jsonNANLst.sort(sortByNANFCDesc);
jsonNumLst.sort(sortByNumFCDesc);
}
if(jsonNumLst.length>0 || jsonNANLst.length>0){
filteredData = [];
if(this._sortOrder == undefined || this._sortOrder == 'asc'){
$.each(jsonNumLst, function(inx, obj) {
filteredData.push(obj);
});
if(filteredData.length == jsonNumLst.length){
$.each(jsonNANLst, function(inx, obj) {
filteredData.push(obj);
});
}
}else if(this._sortOrder == 'desc'){
$.each(jsonNANLst, function(inx, obj) {
filteredData.push(obj);
});
if(filteredData.length == jsonNANLst.length){
$.each(jsonNumLst, function(inx, obj) {
filteredData.push(obj);
});
}
}
}
if((filteredData.length>0) && filteredData.length==(jsonNumLst.length+jsonNANLst.length)){
$("#measureImportGrid3").data("JSGrid").data = filteredData;
//isSortGrid = false;
//saveEffectControlData = $('#saveEffectiveControlGrid').jsGrid('option', 'data');
}
}
}
//Ascending order numeric
function sortByNumFCAsc(x,y) {
return x.fundCode - y.fundCode;
}
//Ascending order nonnumeric
function sortByNANFCAsc(x,y) {
return ((x.fundCode == y.fundCode) ? 0 : ((x.fundCode > y.fundCode) ? 1 : -1 ));
}
//Descending order numeric
function sortByNANFCDesc(x,y) {
return ((x.fundCode == y.fundCode) ? 0 : ((y.fundCode > x.fundCode) ? 1 : -1 ));
}
//Descending order non-numeric
function sortByNumFCDesc(x,y) {
return y.fundCode - x.fundCode;
}

Free JQGrid - save-button in inlineNav not working when adding a second row

we've several Free JQGrids and a problem with adding new rows.
Click on the icon in inlineNav (ADD) a new row will be shown up, clicking the SAVE-Icon the first time works fine. But when adding a second row the Save-buttton in inlineNav will not work. Enter-key in the row works. After reload the whole grid, it will work only once again.
Following is the code of the grid
some defaults:
jQuery.extend($.jgrid.defaults,{
autowidth: true, pager:true, pgbuttons:false, pginput:false,
pgtext:false, datatype: "json", mtype: "POST",
rownumbers:true, rowNum:9999,
postData: {"savestate_encrypted" : function() {return $("input[name='savestate_encrypted']").val();}},
ondblClickRow: function (rowid, status, e) {
var $self = $(this), savedRow = $self.jqGrid("getGridParam", "savedRow");
if (savedRow.length > 0 && savedRow[0].id !== rowid) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
$self.jqGrid("editRow", rowid, { focusField: e.target });
},
});
The grid itself:
jQuery("#grid").jqGrid({
url:"....",
jsonReader: {root: "resourceList"},
height: 500,
cmTemplate: { editable: true},
inlineEditing: {keys: true},
editurl: "....",
colModel:[ //Define Table Columns
{name: "name", label:"Name", key:true, hidden:false},
{name: "activeJobs", label:"aktive Jobs", width:250}
],
}).jqGrid("navGrid", {refresh:true, edit:false, del:true, search:false, add:false})
.jqGrid("inlineNav", {save:true, edit:true, add:true})
</script>
I've figured out that the line 15300 (sorry don't know how to find the branch version - 30.Jan 2017) in the grid source will set the "var ind" to false, when clicking on the button, pressing enter-key works perfect
var tmp = {}, tmp2 = {}, postData = {}, editable, k, fr, resp, cv, savedRow, ind = $self.jqGrid("getInd", rowid, true), $tr = $(ind),
opers = p.prmNames, errcap = getRes("errors.errcap"), bClose = getRes("edit.bClose"), isRemoteSave, isError,
displayErrorMessage = function (text, relativeElem)....
As a fast solution I wanted to subsribe on an event and reload the whole grid. But subscribe() seems to be gone (we are switching from the old struts-tag grid to javascript. I think bind is the correct way now, but which event?
ADDITION---------------------------
I've created a working code which will show a similiar problem without Ajax and Json. When clicking ADD, enter the values and then selecting SAVE in the inlineNav Bar everything is OK, but pressing ADD again, enter values and then select SAVE, the edit-mode will stay open. If you use the Enter-Key instead the SAVE-btn it will work.
<!DOCTYPE html>
<html lang="de"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/jquery.jqgrid.src.js"></script>
<link rel="stylesheet" href="js/jquery-ui.min.css">
<link rel="stylesheet" href="js/ui.jqgrid.min.css">
</head>
<script type="text/javascript">
/* DEFAULTS */
jQuery.extend($.jgrid.defaults,{
autowidth: true, // nutzt die ganze verfügbare Breite
pager:true, // Fusszeile -
pgbuttons:false, // - ohne Seitenkontrollbuttons
pginput:false, // - ohne Eingabefeld
pgtext:false, // - ohne Text
rownumbers:true, // immer Zeilennummern
rowNum:9999, // bis zu 9999 Zeilen
ondblClickRow: function (rowid, status, e) {
var $self = $(this), savedRow = $self.jqGrid("getGridParam", "savedRow");
if (savedRow.length > 0 && savedRow[0].id !== rowid) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
$self.jqGrid("editRow", rowid, { focusField: e.target });
},
});
// For JSON Response
/* jQuery.extend($.jgrid.inlineEdit,{
restoreAfterError:false,
errorfunc: function( response )
{
var resp = response;
alert("error7");
return false;
},
successfunc: function( response )
{
var resp = response;
var hasNoError = true;
// var hasNoError = (resp.responseJSON.actionErrors.length == 0);
return hasNoError;
}
});
*/
function dataset() {
"use strict";
var mydata2 = [
{ id: "10", name: "test" , value: "5"},
{ id: "20", name: "test20", value: "5"},
{ id: "30", name: "test30", value: "5"},
{ id: "40", name: "test40", value: "5"},
{ id: "50", name: "test50", value: "5"},
];
return mydata2;
};
</script>
<body>
<table id="grid"></table>
<script type="text/javascript">
jQuery("#grid").jqGrid({
data: dataset(),
colModel: [
{ name: "id", label:"ID"},
{ name: "name", label:"NAME", align: "center" },
{ name: "value", label:"VALUE", align: "center" }
],
cmTemplate: { editable: true, autoResizable: true },
}).jqGrid("navGrid", {refresh:true, edit:false, del:true, search:false, add:false})
.jqGrid("inlineNav", {save:true, edit:true, add:true})
</script>
</body></html>
If I correctly understand your problem then you want to reload the grid after saving. You can use jqGridInlineAfterSaveRow event for the purpose:
jQuery("#grid").on("jqGridInlineAfterSaveRow", function () {
setTimeout(function () {
jQuery("#grid").trigger("reloadGrid");
}, 0);
});

How to create custom dropdownlist in kendo grid header column?

Actually my requirement is want to create custom dropdownlist in the column header of kendo grid. I don't down like nrwant to use filtler column. I just want to add normal dropdown in header. Please provide any example like that so that i can move forward on my task.
Thanks in advance...
In your column definition add a property like this:
headerTemplate: '<input id="dropdown" />'
Then after your grid initialization do:
$("#dropdown").kendoDropDownList({...init parameters...});
UPDATE: go to dojo.telerik.com and paste in the following code:
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [
{
field: "ProductName",
title: "Product Name",
headerTemplate: '<input id="dropdown" />'
},
{ field: "UnitPrice", title: "Price", template: 'Price: #: kendo.format("{0:c}", UnitPrice)#' }
],
pageable: true,
dataSource: {
transport: {
read: {
url: "http://demos.telerik.com/kendo-ui/service/products",
dataType: "jsonp"
}
},
pageSize: 10
},
excelExport: function(e) {
var sheet = e.workbook.sheets[0];
var template = kendo.template(this.columns[1].template);
for (var i = 1; i < sheet.rows.length; i++) {
var row = sheet.rows[i];
var dataItem = {
UnitPrice: row.cells[1].value
};
row.cells[1].value = template(dataItem);
}
}
});
$("#dropdown").kendoDropDownList({
optionLabel: 'Choose a value...',
dataTextField: 'description',
dataValueField: 'id',
dataSource:{
data: [{id: 1, description: 'One'},{id: 2, description: 'Two'}]
},
change: function(e){
//do whatever you need here, for example:
var theGrid = $("#grid").getKendoGrid();
var theData = theGrid.dataSource.data();
$(theData).each(function(index,item){
item.ProductName = e.sender.text();
});
theGrid.dataSource.data(theData);
}
});

Hide column in jQuery MultiColumn Autocomplete

I have a fine working jquery multicolumn autocomplete. Now i have to add a column which should be hidden. Basically its a ID of the values. So when the user selects the value i could able to get the ID of the selected row.
//Code:
<script type="text/javascript">
var autocompleteSource;
var colValues = [];
var columns = [{ name: 'Workflow Name', width: '200px' }, { name: 'Workflow Category', width: '150px' }, { name: 'Status', width: '100px' }, { name: 'Workflow Owner', width: '150px' }];
$.ajax({
url: "/Home/LoadWorkflowDropdown",
datatype: 'json',
mtype: 'GET',
success: OnComplete,
error: OnFail
});
function OnComplete(result) {
autocompleteSource = $.parseJSON(result)
$.each(autocompleteSource, function () {
colValues.push([this.WorkflowName, this.WorkflowCategory, this.StatusName, this.UserName]);
});
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var self = this,
thead;
if (this.options.showHeader) {
table = $('<div class="ui-widget-header" style="width:100%"></div>');
$.each(this.options.columns, function (index, item) {
table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
$.each(items, function (index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function (ul, item) {
var t = '',
result = '';
$.each(this.options.columns, function (index, column) {
t += '<span style="padding:0 4px;float:left;width:' + column.width + ';">' + item[column.valueField ? column.valueField : index] + '</span>'
});
result = $('<li></li>').data('item.autocomplete', item).append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>').appendTo(ul);
return result;
}
});
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colValues,
select: function (event, ui) {
this.value = (ui.item ? ui.item[0] : '');
return false;
}
});
}
</script>
Working Fiddle here
Here i have modified js code to add unique id to each record and to get that value when user selects a particular option from the auto-suggest list. Fiddle
HTML: Create a hidden field to store the id of selected option
<input type="hidden" name="selectedId" id="selectedId" />
JS: Added ids in the array and retrieved those ids in select function by index value.
var columns = [{
name: 'Color',
width: '100px'},
{
name: 'Hex',
width: '70px'}],
colors = [['Red', '#f00', '1'], ['Green', '#0f0', '2'], ['Blue', '#00f', '3']];
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colors,
select: function(event, ui) {
$('#selectedId').val(ui.item[2]);
this.value = (ui.item ? ui.item[0] : '');
return false;
}
});

Slickgrid 3 grouping how to remove totals row?

I use multi-row grouping and put the totals in the grouping headers.
I'm not using the totals in the totals rows. I see the the rows are grouped and where the totals would be there are empty rows. In my case there is an empty row after each of the child grouping and at the end there is an empty row for the parent totals.
How do I remove these totals rows?
Thank you!
.cshtml:
<div id="gridList" class="grid" style="width: 100%; height: 500px"></div>
.js
$(function() {
var columns = [
{
id: "isExcluded",
name: "Exclude",
field: "isExcluded" /*, width: 120*/,
formatter: Slick.Formatters.Checkmark,
editor: Slick.Editors.Checkbox, sortable: true
},
{
id: "symbol",
name: "Symbol",
field: "symbol",
sortable: true /*, width: 120*/
},
{
id: "price",
name: "Price",
field: "price",
sortable: true
//, groupTotalsFormatter: sumTotalsFormatter
},
{
id: "parent_name",
name: "Parent Name",
field: "parent_name",
sortable: true /*, width: 120*/
},
{
id: "description",
name: "Description",
field: "description",
sortable: true,
width: 120,
editor: Slick.Editors.Text,
},
{ id: "cancel_ind",
name: "Canceled",
field: "cancel_ind",
sortable: true, width: 80 }
];
function requiredFieldValidator(value) {
if (value == null || value == undefined || !value.length) {
return { valid: false, msg: "This is a required field" };
} else {
return { valid: true, msg: null };
}
};
var options = {
editable: true,
enableAddRow: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true,
enableExpandCollapse: true,
rowHeight: 25
};
var sortcol = "parent_name";
var sortdir = 1;
var grid;
var data = [];
var groupItemMetadataProviderTrades = new Slick.Data.GroupItemMetadataProvider();
var dataView = new Slick.Data.DataView({ groupItemMetadataProvider: groupItemMetadataProviderTrades });
dataView.onRowCountChanged.subscribe(function (e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function (e, args) {
grid.invalidateRows(args.rows);
grid.render();
});
function groupByParentAndSymbol() {
dataViewTrades.setGrouping([
{
getter: "parent_name",
formatter: function(g) {
return "Parent: " + g.value + " <span style='color:green'>(" + g.count + " items) Total: " + g.totals.sum.price + "</span>";
},
aggregators: [
new Slick.Data.Aggregators.Sum("price")
],
aggregateCollapsed: true
,lazyTotalsCalculation: true
},
{
getter: "symbol",
formatter: function(g) {
return "Symbol: " + g.value + " <span style='color:green'>(" + g.count + " items) Total: " + g.totals.sum.price + "</span>";
},
aggregators: [
new Slick.Data.Aggregators.Sum("price")
],
collapsed: true
,lazyTotalsCalculation: true
}]);
};
grid = new Slick.Grid("#gridList", dataView, columns, options);
grid.registerPlugin(groupItemMetadataProviderTrades);
grid.setSelectionModel(new Slick.RowSelectionModel());
..... /*sorting support etc*/
// use instead of the default formatter <--- removed not used.
function sumTotalsFormatter(totals, columnDef) {
var val = totals.sum && totals.sum[columnDef.field];
//if (val != null) {
// return "total: " + ((Math.round(parseFloat(val) * 100) / 100));
//}
return "";
}
// will be called on a button click (I didn't include the code as irrelevant)
var getDataList = function () {
$.getJSON('/Home/GetData/', function (json) {
data = json;
dataView.beginUpdate();
dataView.setItems(data);
groupByParentAndSymbol();
dataView.endUpdate();
dataView.syncGridSelection(grid, true);
});
};
getDataList();
});
Adding displayTOtalsRow: false to the dataview solved my problem - the total rows are not shown now.
var dataView = new Slick.Data.DataView({ groupItemMetadataProvider: groupItemMetadataProviderTrades, displayTotalsRow: false });
To answer simply to your question... Just remove the aggregators: [...], when I say remove you have 2 options, you can remove whatever is the array [...] or you could simply erase completely that object line (so removing completely the aggregators[...]).
Now if you want more explanation of how it works...Let's give you some definition so you'll understand better. An aggregate is a collection of items that are gathered together to form a total quantity. The total in question could be a sum of all the fields, an average or other type of aggregator you might define. So basically it's the action of regrouping by the column you chose and give the calculation result of the group. Alright now how does it work in the case of a SlickGrid? You need to define what kind of Aggregator you want to use (Avg, Sum, etc...) that goes inside your function groupByParentAndSymbol(), defining them will do the calculation BUT unless you attach it to the field, nothing will be displayed, so in the example you found it is very important to attach/bind this groupTotalsFormatter: sumTotalsFormatter to your columns definition, as for example:
...var columns = [{id: "cost", ...width: 90, groupTotalsFormatter: sumTotalsFormatter}, ...];
so let's recap... Once the Aggregator is define new Slick.Data.Aggregators.Sum("cost") it will do the calculation but unless it's bind to the field nothing will be displayed. As an extra option, the aggregateCollapsed (true/false) is to display the sub-total (avg, sum or whatever) inside or outside the group when you collapse.

Categories