JqGrid - Freeze columns - jqgrid

I read all the posts regarding freezing column. But still I am unable solve my problem.
When I called setFrozenColumns my column has frozen but along with another column header is added to the grid. So the column headers one more than the columns. How to resolve this. Here is my over view of code.
makeJqueryGridInstance(grid, gridSettings);
window.prepareSortableColumns(grid);
makefrozenColumns(grid);
function makeFrozenColumn( grid )
{
var colmodel = grid.jqGrid('getGridParam', 'colModel');
if (colmodel[0].name === 'cb')
{
grid.jqGrid('setColProp', colmodel[0].name, { frozen: true });
grid.jqGrid('setFrozenColumns');
fixPositionsOfFrozenDivs.call(grid[0]);
}
}
function prepareSortableColumns(grid)
{
var gridSettings = grid.data('settings');
var gridId = gridSettings.gridId;
var columnHeaders = $("#" + "gview_" + gridId.replace("#", "")).find(".ui-jqgrid-htable > thead > tr > th");
var colModel = grid[0].p.colModel;
$.each(columnHeaders, function (index, columnHeader)
{
if (colModel[index].sortable == false)
{
$(columnHeader).find("div").removeClass("ui-jqgrid-sortable");
}
});
}
For the first time, it is working fine and the column has frozen.
But second time when the call made to prepareSortableColumns(grid), the columnHeader having one more than colModel (I debugged through devTools). So I am getting error for that particular columnHeader sortable is undefined.
Can anybody help me with this. Thanks in advance.

The code of prepareSortableColumns seems be wrong. Its not oriented on dives added in case of usage of frozen columns (see the answer for more details and use Developer Tools to examine the structure of the grids). You can try to use grid[0].grid.headers array instead of selecting columnHeaders in the way like you do this.
Additionally it's in general wrong to remove ui-jqgrid-sortable class. The meaning of the class will be frequently misunderstood because of the name. Non-sortable columns have to have the class too. What you need to do instead is to set CSS style cursor: default on the headers. See the old answer for the corresponding code example.

Related

Kendo Grid: Removing dirty cell indicators

I have been looking at a way to save off my client side edited grid data automatically when the user changes to another row (just like in access, sql management studio etc). It really seems to be a bit of a challenge to do.
One scheme was to use the data source sync, but this ha the problem of loosing our cell position (it always jumped to cell 0, 0).
I have been shown some clever work arounds (go back to the cell after the case, which by the way is hugely appreciated thanks),
but it after some lengthy testing (by myself and others) seemed to be a little "glitchy" (perhaps I just need to work on this more)
At any rate, I wanted to explore perhaps not using this datasource sync and perhaps just do the server side calls "manually" (which is a bit is a pity, but if that's what we need to do, so be it). If I do this, I would want to reset the cell little red cell "dirty" indicators.
I thought I could use something similar to this scheme (except rather than resetting the flag, I want to unset).
So, as in the above link, I have the following..
var pendingChanges = [];
function gridEdit(e) {
var cellHeader = $("#gridID").find("th[data-field='" + e.field + "']");
if (cellHeader[0] != undefined) {
var pendingChange = new Object();
pendingChange.PropertyName = e.field;
pendingChange.ColumnIndex = cellHeader[0].cellIndex;
pendingChange.uid = e.items[0].uid;
pendingChanges.push(pendingChange);
}
}
where we call gridEdit from the datasource change..
var dataSrc = new kendo.data.DataSource({
change: function (e) {
gridEdit(e);
},
Now assuming we have a callback that detects the row change, I thought I could do the following...
// clear cell property (red indicator)
for (var i = 0; i < pendingChanges.length; i++) {
var row = grid.tbody.find("tr[data-uid='" + pendingChanges[i].uid + "']");
var cell = row.find("td:eq(" + pendingChanges[i].ColumnIndex + ")");
if (cell.hasClass("k-dirty-cell")) {
cell.removeClass("k-dirty-cell");
console.log("removed dirty class");
}
}
pendingChanges.length = 0;
// No good, we loose current cell again! (sigh..)
//grid.refresh();
When this didn't work, I also tried resetting the data source dirty flag..
// clear dirty flag from the database
var dirtyRows = $.grep(vm.gridData.view(),
function (item) {
return item.dirty == true;
})
if (dirtyRows && dirtyRows.length > 0) {
dirtyRows[0].dirty = false;
}
demo here
After none of the above worked, I tried the grid.refresh(), but this has the same problem as the datasource sync (we loose our current cell)
Would anyone have any idea how I can clear this cell indicator, without refreshing the whole grid that seems to totally loose our editing context?
Thanks in advance for any help!
Css :
.k-dirty-clear {
border-width:0;
}
Grid edit event :
edit: function(e) {
$("#grid .k-dirty").addClass("k-dirty-clear"); //Clear indicators
$("#grid .k-dirty").removeClass("k-dirty-clear"); //Show indicators
}
http://jsbin.com/celajewuwe/2/edit
Simple solution for resolve that problem is to override the color of the "flag" to transparent.
just override the ".k-dirty" class (border-color)
just adding the above lines to your css
CSS:
//k-dirty is the class that kendo grid use for mark edited cells that not saved yet.
//we override that class cause we do not want the red flag
.k-dirty {
border-color:transparent transparent transparent transparent;
}
This can also be done by applying the below style,
<style>
.k-dirty{
display: none;
}
</style>

YUI datatable conditional dropdown editor

I'm currently editing an application which uses YUI 2.5. I haven't used it before and could use some help.
I want to be able to add a dropdown editor for a particular column's rows using datatable, but I only want it to appear if specific values appear in another column in the corresponding row.
Is it possible to add some kind of If statement in the column definitions? Would I have to use a custom formatter?
eg.
var eventColumnDefs = [
{key:"event_id", sortable:false},
{key:"event_name", sortable:true},
{key:"extended", sortable:true, formatter: function (o) {
if (event_name=type1||event_name=type4||event_name=type5) {
editor:"dropdown", editorOptions:{dropdownOptions:eventData.extendedList}
}
}
}];
I know this code wouldn't work, by the way, I would just appreciate a bit of guidance.
You are close. In the column definition you add the information about the dropdown editor as if you always wanted it to show up. Now, going to the code sample here: http://developer.yahoo.com/yui/datatable/#cellediting
See the last line that attaches onEventShowCellEditor to whatever event you want to make the editor pop up? That is where you put the conditional. Instead of just asking to show the cell editor under any circumstance, you put some code there, like:
myDataTable.subscribe("cellClickEvent", function (ev) {
if ( ** whatever ** ) {
this.myDataTable.onEventShowCellEditor.apply(this, arguments);
}
});
I haven't been doing YUI2 for quite some time now so I don't remember the details on the arguments received by the event listener. I believe that you might also use showCellEditor() instead of onEventShowCellEditor, the later only massages the arguments as received from the event listener and ends up calling showCellEditor so you might as well skip it.
Found a hacky solution as follows
In Column Definitions:
var eventColumnDefs = [
{key:"player_name", sortable:true, editor:"dropdown", editorOptions:{dropdownOptions:currenteam}}
];
Then later on in initialiseTables:
eventDataTable.subscribe("cellClickEvent", function(ev) {
var target, column, field;
target = ev.target;
column = this.getColumn(target);
if (column.key === "player_name") {
field= this.getRecord(target).getData("team_id");
}
if (hometeamlistID == field) {
currenteam=hometeamlist;
} else if (awayteamlistID == field) {
currenteam=awayteamlist;
}
eventDataTable._oColumnSet._aDefinitions[8].editorOptions.dropdownOptions = currenteam;
});
hometeamlist, awayteamlist, hometeamlistID and awayteamlistID are pulled from an XML string. I haven't included that code above, but some of it is included in my question here:
YUI 2.5. Populating a dropdown from XML

jqGrid how can I hide subgrid if it empty?

How can i hide a subgrid if it empty?
I tried this solution and this but no luck.
Look at the old answer. It seems be exactly what you need.
Based on this and Oleg's answer i resolve my problem.
In my table all rows are expanded so code looks like this for main table:
gridComplete: function(){
var table_name = 'table_18';
var myGrid = $('#'+table_name);
var rowIds = myGrid.getDataIDs();
$.each(rowIds, function (index, rowId){
myGrid.expandSubGridRow(rowId);
});
var subGridCells = $("td.sgexpanded",myGrid[0]);
$.each(subGridCells,function(i,value){
$(value).unbind('click').html('');
});
}
In this code i removed click action for expand/collapse subgrids. So they are always open and there is no posibility to collapse them.
Based on this i remove empty subgrids.
loadComplete: function(){//in subgrid
var table_value = $('#'+subgrid_table_id).getGridParam('records');
if(table_value === 0){
$('#'+subgrid_id).parent().parent().remove();
}
}
Maybe exist more simple and elegant solution, but for me it's works as i expected.

How to enable click in edit action button if new row is saved jqgrid

Edit formatter action button is placed to jqgrid column:
colModel: [{"fixed":true,"label":" change ","name":"_actions","width":($.browser.webkit == true? 37+15: 32+15)
,"align":"center","sortable":false,"formatter":"actions",
"formatoptions":{"keys":true,"delbutton":false,"onSuccess":function (jqXHR) {actionresponse = jqXHR;return true;}
,"afterSave":function (rowID) {
cancelEditing($('#grid'));afterRowSave(rowID,actionresponse);actionresponse=null; }
,"onEdit":function (rowID) {
if (typeof (lastSelectedRow) !== 'undefined' && rowID !== lastSelectedRow)
cancelEditing($('#grid'));
lastSelectedRow = rowID;
}
}}
New row is added to jqgrid in loadcomplete event
var newRowData = {};
var newRowId = '_empty' + $.jgrid.randId();
$('#grid').jqGrid('addRowData', newRowId, newRowData);
and its id is updated if save action button is clicked:
function aftersavefunc(rowID, response) {
restoreActionsIcons();
$('#grid').jqGrid('resetSelection');
var json = $.parseJSON(response.responseText);
$("#" + rowID).attr("id", json.Id);
lastSelectedRow = json.Id;
$("#grid").jqGrid('setSelection', lastSelectedRow);
}
After clicking save action button edit action button clicks are ignored. It is not possible to re-enter to edit mode after first editing.
How to fix this so that row can edited by edit button click again after saving ?
Update
I added $(this).focus() as suggested in Oleg answer and also wrapped id change into setTimeout as Oleg recommends in other great answer:
function aftersavefunc(rowID, response) {
restoreActionsIcons();
$(this).focus();
$('#grid').jqGrid('resetSelection');
var json = $.parseJSON(response.responseText);
setTimeout(function () {
$("#" + rowID).attr("id", json.Id);
lastSelectedRow = json.Id;
$("#grid").jqGrid('setSelection', lastSelectedRow);
}, 50);
}
Problem persists. The problem may related to row id change since:
It occurs only in last row (where id is changed after save). It does not occur for saved rows where responseText returns same id and row id is actually not changed.
It does not occur if cancel action button is pressed.
Maybe row id needs additional reset id addition to resetSelection or needs updated in somewhere other place also.
Update2
I added code form updated answer to errorfunc and used only english characters and numbers id ids. This allows to click multiple times but introduces additional issue:
extraparam is no more passed. If rowactions() calls are commented out, extraparam is passed with with rowactions calls extraparam is not passed.
I changed jqGrid source code and added alert to rowactions method:
alert( cm.formatoptions);
if (!$.fmatter.isUndefined(cm.formatoptions)) {
op = $.extend(op, cm.formatoptions);
}
In first clicks alert outputs 'Object'. In succeeding clicks to Save button it outputs undefined. So for unknown reason formatoptions is cleared.
Remarks to comment:
Absolute url in testcase is not used. Datasource is set to localarray.
I verified that testcase works in IE and FF without external url access.
For extraparam issue I can create new testcase.
Without image directory buttons are shown in cursor is moved over them.
Missing image directory still allows to reproduce the issue.
FormData function is defined in js file.
Since new issue occurs after adding rowactions() calls and does not occur if those calls are removed, this seems to be related to the code proposed in answer.
I suppose that the problem exist because one hide a button which has currently focus. Look at the code from the answer. If one remove the line $(this).focus(); // set focus somewhere one has the same problem as you describes. So I suggest that you just try to set somewhere, for example in restoreActionsIcons the focus to any the table element of the grid after hiding the button having currently the focus. I can't test this, but I hope it will help.
UPDATED: I examined your problem one more time and I hope I can suggest you a solution.
You problem can be divided on two sub-problems. The main your problem is the the changing of the id of the row. So it is not common problem which everybody has.
The problem is that "actions" formatter create onclick functions directly in the HTML code (see for example here):
ocl = "onclick=$.fn.fmatter.rowactions('"+rowid+"','"+opts.gid+"','edit',"+opts.pos+");..."
So the functions will contains the original rowid. To fix the problem you can modify the code fragment of your aftersavefunc inside of setTimeout from
$("#" + rowID).attr("id", json.Id);
lastSelectedRow = json.Id;
$("#grid").jqGrid('setSelection', lastSelectedRow);
to something like the following:
var $tr = $("#" + rowID),
$divEdit = $tr.find("div.ui-inline-edit"),
$divDel = $tr.find("div.ui-inline-del"),
$divSave = $tr.find("div.ui-inline-save"),
$divCancel = $tr.find("div.ui-inline-cancel");
$tr.attr("id", json.Id);
if ($divEdit.length > 0) {
$divEdit[0].onclick = function () {
$.fn.fmatter.rowactions(newId,'grid','edit',0);
};
}
if ($divDel.length > 0) {
$divDel[0].onclick = function () {
$.fn.fmatter.rowactions(newId,'grid','del',0);
};
}
if ($divSave.length > 0) {
$divSave[0].onclick = function () {
$.fn.fmatter.rowactions(newId,'grid','save',0);
};
}
if ($divCancel.length > 0) {
$divCancel[0].onclick = function () {
$.fn.fmatter.rowactions(newId,'grid','cancel',0);
};
}
lastSelectedRow = json.Id;
$("#grid").jqGrid('setSelection', lastSelectedRow);
The second problem is that you use special characters inside of ids. I found a bug in the $.fn.fmatter.rowactions which need be fixed to support special characters in ids. The problem is that in the line 407 of jquery.fmatter.js the original rowid parameter rid will be changed:
rid = $.jgrid.jqID( rid )
and later everywhere will be used modified id. For example in the id is my.id the encoded version will be my\\.id. It's correct for the most places of the $.fn.fmatter.rowactions code (see here), but it' s incorrect as the rowid parameter of the editRow, saveRow, restoreRow, delGridRow, setSelection and editGridRow (see the lines 433-453). So the code must be fixed to use the original not escaped (not encoded) rid value with which the $.fn.fmatter.rowactions was called.
I think I will post tomorrow the corresponding bug report with the suggestions in the trirand forum.
UPDATED 2: The code $.fn.fmatter.rowactions(newId,'grid','edit',0); which I wrote above is just an example. I took it from the test demo which you send me. You should of course modify the code for your purpose. How you can see for example from the line the second parameter of the $.fn.fmatter.rowactions in the id of the grid which you use: 'grid', 'list' of something like myGrid[0].id. The last parameter should be the index of the column having formatter:'actions' in the colModel. You can use getColumnIndexByName function from the answer on your old question to get the index by column name.

How do i automatically append column names to post data sent to php when grid loads or refreshes?

I'm new to jqGrid and jquery and i'm learning as fast as i can but i still am a little lost about how to some things like how to append addition information to the post data in jqgrid that gets sent to php.
It would be nice for the php script to know what columns the grid wants when it initially loads or you press the jqgrid refresh/reload button.
I know i can use the postData option: postData:{name:val,,,}, but i was hoping to just automatically pull the column names from the colModel definitions using this function...
postData: function(){
colmodel = $('#tab4-grid').jqGrid('getGridParam','colModel');
colarray = '{';
for (var i in colmodel) {colarray += '"'+colmodel[i].name+'":"'+colmodel[i].name+'",';}
colarray += '}';
return colarray;
},
so i would not have to spell them out manually again. However, while the function produces the correct code, it's not getting posted. I can't seem to figure out the problem. Can someone help please?
thanks.
The first thing which you have to do is to rewrite
postData: function() { ... }
to
postData: {
myColumnsName: function() { ... }
}
jqGrid already send some standard parameters to the server (page, rows ,...). With the code above you will add and additional parameter with the name myColumnsName which you can fill in any way inside of the function body.
You current implementation is very dirty. You don't define local variables colmodel and colarray. Moreover you try to serialize array of strings as object ('{}') and not as array ('[]'). You should not use for (var i in colmodel) construction if you enumerate array items for (var i=0; i<colmodel.length; i++) is better. Additionally 'colModel' contain some column names ('rn', 'cb', 'subgrid') which you should skip in the enumeration. You can define as var colNames = []; and use colNames.push to fill it. Then you can use standard JSON.stringify method from json2.js to convert array to the JSON string.

Resources