I am using jqGrid and want to save column widths after they are resized - jqgrid

I added the resizeStop event to my grid and it gets called, but I need to save the new column widths in the session and then use the new values to maintain the user preferences for column widths. Currently paging in the grid or reloading resets the column widths.
Here is what I have so far.
resizeStop: function(newwidth, index) {
alert(index + " : " + newwidth);
}

OK, I got it. I store all column widths in a HashMap in a bean I use to save session info. When the resizeStop event is fired I submit the new column size to a controller (I'm using Java and Spring) which updates the values in the HashMap.
Here are the code snippets:
resizeStop: function(newwidth, index) {
var colModel = $("#list").jqGrid('getGridParam','colModel');
$.post("/sessionState/columnWidth/update",
{
column: colModel[index].name,
width: newwidth
}
)
}
and in the colModel:
{name:'Title', index:'title', width: ${uiState.columnWidthMap["Title"]}, jsonmap: 'title', sorttype: "text"}

Related

Dynamic cell height in slickgrid?

I have to display cell content like
Policy
Part
Cert
Separated with next line character
In slickgrid table and so on.
How can I do this?
I searched but nothing worked for me.
What should I do with this is there any way to fit contents by height.
I Have this code written for breaking cells
columnname: <p>+policy+</p><br/>+part......and so on.
Any lead will be highly appreciated.
Better register a new formatter for your column.
Example
function myformatter(row, cell, value, columnDef, dataContext) {
return "<style='text-decoration: underline;color: #669900;height:120px;'>" + value +";
}
And call myformatter into column definition
var columns = [];
columns[0] = { id: "id", name: "columnname", field: "id", sortable: true, width: 5, formatter: myformatter };

JqGrid Performance - setRowData lags

setRowData takes almost 5 seconds when the grid has 300 rows, 30 cols, and 4 frozen cols.
$("#tbl").jqGrid({
gridview: true,
url: '../controller/GetData',
datatype: "json",
rowNum: pageSize,
viewrecords: true,
loadtext: '',
loadui: 'disable',
rowList: [1000, 2000, 3000],
width: $(window).width() - LeftMargin,
shrinkToFit: false,
pager: '#dvPager',
pagerpos: 'left',
colNames: GetColNames(selectedViewName, viewCols),
colModel: GetColModel(selectedViewName, viewCols),
cmTemplate: {
title: false
},
recordtext: "Displaying {0} - {1} of {2}",
rowattr: function (rowData) {
},
//onCellSelect: function (rowid, iCol, cellcontent, e) {
// e.stopPropagation();
// proto.editcell(rowid, iCol, cellcontent, e);
//},
loadComplete: function (data) {..},
onPaging: function (data) {..},
serializeGridData: function (postData) {..}
});
Can you please guide me with the performance tuning tips?
In GetColModel we are binding columns as follows -
'Discount': {
name: 'Discount', index: 'Discount', width: colModelWidthDict['Discount'], title: false, sortable: false, resizable: colResizable, hidden: !bReadCalculationSellInfo,
formatter: function (cellValue, option, rowObject) {
if (rowObject.level == 0 || (rowObject.Flag == 0 && (rowObject.Discountable && rowObject.Discountable.toLowerCase() == 'no')))
return '';
else {
if (!proto.IsReadOnly(rowObject) && ((rowObject.Flag == 0 && (rowObject.Discountable && rowObject.Discountable.toLowerCase() == 'yes')) || rowObject.Flag > 0))
return proto.GetControls("Discount", option.rowId, "Numeric", rowObject.Discount, 6, 90)
else
return '<span class="amt">' + cellValue + '</span>';
}
},
unformat: function (cellValue, option) {
return cellValue;
},
cellattr: function (rowId, val, rowObject, cm, rdata) {
if (parseInt(rowObject.PPPChngDisc) == 1)
return ' style="color:red"';
}
}
//code for colModel - 1 column above
In general you should prefer to modify only small number of rows. If you modify one row then the web browser have to recalculate position of all other rows (500 rows) of the grid. In the case modifying 300 rows means 300*500 operations for the web browser.
If you fill the whole grid and you use gridview: true option then jqGrid places at the beginning all the data for the grid body in array of strings. After preparing of all information in string format jqGrid place the whole body of the grid as one operation. It's just one assigning innerHTML property of tbody. Thus it's more effective to reload the whole grid as to make modification of many rows of the grid in the loop using setRowData.
So I would recommend you to reload the grid in your case.
Moreover you should consider to reduce the number of rows in the page of grid. If you use rowNum: 500 you just reduce the performance of your page tin many times without any advantage for the user. The user can see about 20 rows of the data only. Only if the user scrolls he/she is able to see another information. In the same way the user could click next page button. Holding 500 rows force web browser make a lot of unneeded work. Modifying of the first row from 500 the web browser have to recalculate position of all 500 rows. Even if the user move the mouse over a row the web browser change the class of the hovering row and it have to recalculate position of all other from 500 rows event the rows are not visible.
One more remark. The implementation of frozen columns in jqGrid 4.6 is slow. Starting with the end of 2014 and publishing 4.7.1 with changing Lisanse and making jqGrid commercial I develop free jqGrid as fork based on jqGrid 4.7 (see the readme for more details). I implemented a lot of changes and new features in the fork. The recent changes includes many improvement of frozen columns feature. If you loads free jqGrid or just try it directly from GitHub by including the corresponding URLs (see the wiki) you will see that the performance of frozen columns is dramatically improved. Additionally frozen columns supports now row and cell editing in all editing modes. I plan to publish free jqGrid 4.9 soon. So I recommend you to try it.
UPDATED: You posted the code, which you use in comments below. I see the main problem in the implementation of Process function which will be called on change in the <input> fields on the grid. I recommend you to try something like this one:
function Process(contrl) {
var $cntrl = $(contrl),
$td = $cntrl.closest("tr.jqgrow>td"),
$tr = $td.parent(),
rowId = $tr.attr("id"),
newValue = $cntrl.val(),
$grid = $("#list"),
p = $grid[0].p,
colModel = p.colModel,
columnName = colModel[$td[0].cellIndex].name, // name of column of edited cell
localRowData = $grid.jqGrid("getLocalRow", rowId),
iColTotal = p.iColByName.total;
// modify local data
localRowData[columnName] = newValue;
localRowData.total = parseInt(localRowData.quantity) * parseFloat(localRowData.unit);
// modify the cell in the cell (in DOM)
//$grid.jqGrid("setCell", rowId, "total", localRowData.total);
$($tr[0].cells[iColTotal]).text(localRowData.total);
return false;
}
One can event improve the code and not use setCell at all. It's important to understand that local grid hold the data in the form of JavaScript object. The access to the data is very quickly. You can modify the data without any side effects existing with DOM elements. In the above code I use only relative search inside of the DOM of the row using closest and parent. It works very quickly. I recommend to save $("#list") in the variable outside of the Process (move var $grid = $("#list") in the outer function) and just use $grid variable. It will make access to the DOM of page very quickly. The line localRowData = $grid.jqGrid("getLocalRow", rowId) get the reference to internal JavaScript data object which represent the internal data of the row. By modifying the data by localRowData[columnName] = newValue; or localRowData.total = ... we make the half of job. One need only to change the value in the DOM on the cell Total. I used iColByName which exist in the latest sources of free jqGrid on GitHub. It get just the column index in colModel by column name. One can find the same information alternatively if one use more old jqGrid. The line $($tr[0].cells[iColTotal]).text(localRowData.total); shows how to assign manually the data in the cell. It's the most quick way to do this, but one assign the data without the usage formatter. For more common case (for example in case of frozen "total" column) one can use the commented row above: $grid.jqGrid("setCell", rowId, "total", localRowData.total);.

jqGrid: setCell clears the column value

I am trying to update the cell value of a particular column in my grid. I am using local JSON for populating the grid datatype: "local".
The column definition of that column is as follows:-
{
name: 'details',
index: 'details',
label: 'Details',
editable: false,
align: 'center',
formatter: function(cellvalue, options, rowObject) {
if (rowObject['verified']) {
return 'sdfsfsd'; // actually hyperlink for the cellvalue
}
return '';
}
}
I am using the following line of code to update the cell value:-
// rowid is 1
grid.jqGrid('setCell', 1, 'details', 'DONE!');
Also tried like this:
// the last parameter true to force update
grid.jqGrid('setCell', 1, 'details', 'DONE!', null, null, true);
However, the cell value is cleared out (cell becomes empty, <td> content is empty). This happens only for this column, and not for other columns in the grid. What am I missing?
Thanks
Vivek Ragunathan
If you use custom formatter you should specify unformatter too. The function formatter will be used to set the value in the cell. At the beginning of cell editing jqGrid need to get the value from the cell. The function unformat do the job.

Sort comboboxes of a gridpanel column

In a column a of a grid panel I use a combobox as editor and a renderer to display values :
editor: {
xtype: 'combobox',
alias: 'bienTypeCombobox',
store: 'BienTypesStore',
valueField: 'id_bien_type',
displayField: 'nom',
autoHeight: true,
editable: false,
autoSelect: true,
allowBlank: false
},
renderer: function (value, metaData, record, rowIndex, colIndex, store, view) {
var display = '';
Ext.data.StoreManager.get("BienTypesStore").each(
function (rec) {
if (rec.get('id_bien_type') === value) {
display = rec.get('nom');
return false;
}
});
return display;
}
So, when the cells are edited the combo box is displayed and when the cells are not edited the displayField of this combo box is displayed.
My problem is that for now,, when I click on the header of this column, the rows are sorted by the valueField of the combo box.
I would like to make the user able to sort this column by the displayedField of the combo box.
Please help, thanks
I don't think there is easy solution for this. The only one way I can think of is the following:
Create a virtual field in your model (with display field basically). Create convert function for this virtual field, so when it's set real value field is get updated.
Use this virtual field in the grid without additional rendered
Use editor for this field with both valueField and displayField pointing to this field.

How to supply a Row ID when using jqGrid 'editGridRow' to create a new row and not the auto generated Row ID jqg1

I'm new to jqGrid, so hopefully someone can point me in the right direction.
Basically, I am using jgGrid to display a list of dates and costs that I have read in from a file that I want the user to be able to amend or add new entries or delete existing entries. Upon the user clicking an onscreen button "Apply" to post back the form , I read out the jqGrid and post back to Server in the form of a JSON string.
My problem is that when I add new rows (via 'editGridRow'), jqGrid is using it's autogenerated jqg1, jg2, jg3, etc and the new rows are being populated at the top of grid instead of at their row id position i.e at the bottom of grid.
I am able to generate RowID's as necessary, however I do not seem to be able to supply them to 'editGridRow' when creating new entries, instead it appears I have to use the keyword "new".
As you are aware the reason I am using editGridRow instead of addRowData is that editGridRow creates a modal dialog for the user to enter the data.
Any help would be appreciated.
This is what I would like to use to supply a row ID:
$("#tableGrid").jqGrid('editGridRow', gridRowID, {reloadAfterSubmit:false});
This is what I have to use to get the code to work:
$("#tableGrid").jqGrid('editGridRow', "new", {reloadAfterSubmit:false});
Here is the code snippet I use for creating the gqGrid in my JSP:
var gridRowID = ${costHistoryEntries}.length
$("document").ready(function() {
$("#tableGrid").jqGrid({
data: ${costHistoryEntries},
datatype: "local",
height: 200,
colNames:['Date', 'Cost'],
colModel:[
{name:'chdate', index:'chdate', width:110, sorttype:"date", editable:true, editrules:{date:true, required:true, custom:true, custom_func:checkDate}, datefmt:'d/m/Y'},
{name:'cost', index:'cost', width:160, align:"right", sorttype:"float", editable:true, editrules:{number:true, required:true}, formatter:'float'},
],
autowidth: true,
loadonce: true,
sortname: 'chdate',
sortorder: "desc",
rowList:[10, 20, 30],
pager: jQuery('#tablePager'),
viewrecords: true,
editurl: '/myurl',
caption: "Cost History Entries" }
);
$("#tableGrid").jqGrid('navGrid', "#tablePager", {edit:true, add:true, del:true, search:true, refresh:true});
$("#addEntry").click(function() {
gridRowID++;
$("#tableGrid").jqGrid('editGridRow', "new", {reloadAfterSubmit:false});
});
});
I also created a button and linked it to "addEntry" as an alternative way to adding a new row using the jqGrid Navigator "add/edit/delete/find/reload" bar. As you can see previous to loading the grid with data I stored the number of entries in gridRowID. What I was hoping to be able to do in the "#addEntry" click function was use the updated gridRowID as a RowID parameter.
As a FYI:
In a previous version of the code I was using the following to load the data into the grid:
var griddata = ${costHistoryEntries};
for (var i=0; i <= griddata.length; i++) {
$("#tableGrid").jqGrid('addRowData', i+1, griddata[i], "last");
}
but found that I could do that same with
data: ${costHistoryEntries},
Both versions correctly create row ID's for the supplied sample data from the server:
[{"chdate":"20/05/2011","cost":"0.111"},{"chdate":"01/06/2011","cost":"0.222"},{"chdate":"07/07/2011","cost":"0.333"}]
My problem is adding new rows of data.
Further update, On the server side, as a test I intercepted the post to /myurl and updated the id from "_empty" to "7" but the new entry in jqGrid still has an autogenerated jqGrid Row ID "jqg1":
Key = chdate, Value = 26/09/2011
Key = oper, Value = add
Key = cost, Value = 14
Key = id, Value = _empty
Updated Key = chdate, Value = 26/09/2011
Updated Key = oper, Value = add
Updated Key = cost, Value = 14
Updated Key = id, Value = 7
I am not quite understand your requirement. You get the input for the jqGrid from the server, but use datatype: "local" instead of the datatype: "json" for example which instruct jqGrid to get ajax request to the server to get the data whenever as needed. Moreover you want to save the date on the server, but use editurl: '/dummyurl' instead of the real server url. The editurl would get the input data from the $("#tableGrid").jqGrid('editGridRow', "new", {reloadAfterSubmit:false}); and should post back the id of the new generated row. Is it not what you want?
So my suggestion would be to use some server based datatype (the bast is datatype: "json") and in the same way use real editurl which save the data on the server (in the database mostly) and place in the server response the id on the new generated data item.
UPDATED: If you use reloadAfterSubmit: false option of the editGridRow you have to use afterSubmit event handler together with reloadAfterSubmit which decode the server response and return the result in the format [true,'',new_id] For example if your server just return new rowid as the data you can use
$("#tableGrid").jqGrid('editGridRow', "new",
{
reloadAfterSubmit: false,
afterSubmit: function (response) {
return [true, '', response.responseText];
}
}
);

Resources