jqGrid rowNum option issue - jqgrid

Assume that row numbers is changed from 10 to 30 in navgrid and that we handle onPaging like so:
...
onPaging: function(pgbtn) {
var rowNum = $(this).getGridParam('rowNum');
return 'stop';
}
In jqGrid 4.4.0 rowNum will be 30.
In jqGrid 4.7.0 rowNum will be 10.
Is this expected behaviour because I think rowNum should be 30?

The order of the execution is changed in (compare the line in jqGrid 4.7.0 with the line in jqGrid 4.4.0). jqGrid first changed the rowNum``and then calledonPaging` in jqGrid 4.4.0, but in jqFeid 4.7.0 the oder is changed.
To access to the new value of rowNum one should get the value of rowNum from the corresponding <select> control directly. If you use the pager at the bottom of the grid then the corresponding code could be the following:
onPaging: function (pgButton) {
var p = $(this).jqGrid("getGridParam"),
newRowNum = parseInt($(p.pager).find(".ui-pg-selbox").val());
if (...) { // some stop criteria
return "stop";
}
}
If you use toppager: true option then jqGrid create the pager on the top of the grid and then it change the value of toppager parameter from true to the selector id of the pager. So you can use the code like
onPaging: function (pgButton) {
var p = $(this).jqGrid("getGridParam"),
newRowNum = parseInt($(p.toppager).find(".ui-pg-selbox").val());
if (...) { // some stop criteria
return "stop";
}
}
which just use p.toppager instead of p.pager in the previous code example.
In case of usage both top and bottom pagers you have to get both values and choose the value which is not equal to the value of rowNum parameter:
onPaging: function (pgButton) {
var p = $(this).jqGrid("getGridParam"),
rowNumBottom = parseInt($(p.pager).find(".ui-pg-selbox").val()),
rowNumTop = parseInt($(p.toppager).find(".ui-pg-selbox").val()),
newRowNum = p.rowNum === rowNumTop ? rowNumBottom: rowNumTop;
if (...) { // some stop criteria
return "stop";
}
}
By the way there are exist close problem in case of calling onPaging after other changing in the pager, for example if the user typed new value in the input box with new pager number.
I'm developing now free jqGrid as my fork on github. I change the code of jqGrid so that onPaging receives the second parameter which is object with the properties newPage, currentPage, lastPage, currentRowNum and newRowNum. The corresponding jQuery event jqGridPaging are added too. Moreover I have changed the value of the first parameter so that it corresponds the documentation and the value will be the string "first", "last", "prev" or "next" in case when the user clicked on the corresponding pager button. The version 4.7 used in reality the id of the corresponding pager buttons instead of "first", "last", "prev", "next". So the strings "first", "last", "prev", "next" could be appended with "_" and the id of the pager (or toppager).
Thus one can just use options.newRowNum or options.currentRowNum directly in the code of callback:
onPaging: function (pgButton, options) {
// one can use options.newRowNum directly
// the value options.currentRowNum is identical to
// $(this).jqGrid("getGridParam", "rowNum")
if (...) { // some stop criteria
return "stop";
}
}

In the case of top and bottom pagers, I would add to Oleg's response:
onPaging: function (pgButton) {
var p = $(this).jqGrid("getGridParam"),
rowNumBottom = parseInt($(p.pager).find(".ui-pg-selbox").val()),
rowNumTop = parseInt($(p.toppager).find(".ui-pg-selbox").val()),
newRowNum = p.rowNum === rowNumTop ? rowNumBottom: rowNumTop;
if (...) { // some stop criteria
return "stop";
}
// update the current value so subsequent changes are detected
p.rowNum = newRowNum;
}
This handles the case that the user changes the value on the top pager, then changes it again on the bottom pager. The code above will keep detecting the top pager value.

Related

bootstrap-multiselect rebuild/refresh not working

I have 2 bootstrap-multiselect boxes. I want to refresh the items in one based on the selections made in the other via an Ajax call.
Everything work except that the that the multiselect uses to disoplay the options is not being populated by either 'rebuild' or 'refresh'.
Code:
Decalring the multiselect"
$('#Groups').multiselect({
onChange: function (option, checked) {
//get all of the selected tiems
var values = $('#Groups option:selected');
var selected = "";
$(values).each(function (index, value) {
selected += $(value).prop('value') + ",";
});
selected = selected.substring(0, selected.length - 1);
//update hidden field with comma delimited string for state persistance
$("#Hidden_Groups").val(selected);
},
includeSelectAllOption: true
});
Updating the options list:
$('#JobCodes').multiselect({
onDropdownHide: function(event) {
console.log("start");
var option = $("#Groups");
//clear out old consolidations
option.empty();
console.log("emptied");
////get consolidation and append to select options list
$.getJSON("/Reports/GetGroups/", { options: $("#Hidden_JobCodes").val() }, function (result) {
$.each(result, function (index, item) {
console.log(item.text);
option.append($("<option />").val(item.id).text(item.text));
});
});
option.multiselect('destroy');
option.multiselect('rebuild');
option.multiselect('refresh');
},
Have left the destroy, rebuild and refresh in just as an example things i have tried. Have used all of these in every order and combination and no luck.
Destroy will "change" my multiselect back to a standard select but no matter what I do after that I cannot get the multiselect to come back with the new list of options, including using the full multiselect call wiht the onchange event present. Its either empty of has the old list. The select list has the correct options present when I make the refresh/rebuild calls.
Thanks in advance.
T
Totally my fault!!
The call to /destroy/refresh/rebuild was outside of the ajax call. so the were executing before my new list had been returned, hence no list to rebuild at that time.
Solution:
////get consolidation and append to select options list
$.getJSON("/Reports/GetGroups/", { options: $("#Hidden_JobCodes").val() }, function (result) {
$.each(result, function (index, item) {
console.log(item.text);
option.append($("<option />").val(item.id).text(item.text));
});
option.multiselect('rebuild')
});

jqGrid Make a Row readonly

I have a grid setup using form editing. I want the the user to be able to edit only some of the rows. As a start, I figured the easiest way to do this was to have a column (probably hidden) in my server query and XML that denotes the Access or Role the user has. So essentially the grid now has a column "Access Role" with 'Y' or 'N' for each row. (where Y = user can edit, N = View/readonly)
I've tried a couple things to implement this. The best I've come up with is using the rowattr function, but my use is flawed since it hides the row in the grid (I don't want it hidden, just readonly):
function (rd) {
console.log('Row = '+rd.WWBPITM_SURROGATE_ID);
if (rd.ACCROLE === "N") {
console.log('RowAttr '+rd.ACCROLE);
return {"style": "display:none"};
}
This might be a start, but I'm not sure where to go from here and I'm not sure if I'm barking up the wrong tree with using rowattr.
I also tried using setCell in a loadComplete function, like this:
function GridComplete() {
var grid = $('#list1');
var rowids = grid.getDataIDs();
var columnModels = grid.getGridParam().colModel;
console.log('Check ACCROLE');
// check each visible row
for (var i = 0; i < rowids.length; i++) {
var rowid = rowids[i];
var data = grid.getRowData(rowid);
console.log('ACCROLE for '+rowid+' is '+data.ACCROLE);
if (data.ACCROLE == 'N') { // view only
// check each column
//console.log(data);
for (var j = 0; j < columnModels.length; j++) {
var model = columnModels[j];
if (model.editable) {
console.log('Is Editable? '+model.editable);
//grid.setCell(rowid, model.name, '', 'not-editable-cell', {editable: false, edithidden: true});
grid.setCell(rowid, model.name, '', 'not-editable-cell', {editoptions: { readonly: 'readonly', disabled: 'disabled' }});
}
}
}
}
}
But the editoptions don't seem to do anything with this.
Any ideas how to do this?
OK thanks for explaining about Form editing. Here's an example of how to prevent edits on certain records for jqGrid with form editing:
Start with this example of jqGrid form edit: http://www.ok-soft-gmbh.com/jqGrid/MulticolumnEdit.htm
Use the beforeInitData event to check your data before the edit form is displayed. Note that this is bound to the pager object.
Use getGridParam and getCell methods to get the current value you want. In my example I grabbed the client name
Add your own business logic for checking (I don't allow edits on 'test2')
Return false to prevent the edit form from popping up.
This example only handles edit, not insert or delete.
Replace $grid.jqGrid("navGrid", "#pager",...) from the example with this:
$grid.jqGrid("navGrid", "#pager", {view: true},
// Events for edit
{
beforeInitData: function (formid) {
var selectedRow = jQuery("#list").jqGrid('getGridParam','selrow'); //get selected rows
var selectedClient = $("#list").jqGrid('getCell', selectedRow, 'name');
if(selectedClient == 'test2')
{
alert('You are not allowed to edit records for client "' + selectedClient + '"');
return false;
}
}
},
// Events for add
{
beforeShowForm: function (formid) {
}
}
);
You didn't provide much information about how you're updating rows (there are various methods as described in JQGrid web page demos, but I took a guess as to a possible solution. I started with the example on the bottom of this page (trirand's web site wiki for inline_editing) http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing and made a few changes.
Added a new data column securityGroup, and put in data like 'A', 'B', 'C'
Displayed the new data column in the grid
The example used the onSelectRow event to start editing a row if you clicked on a new row. I updated this callback to check the value of row['securityGroup'], and only start .editRow if it's in securityGroupA
JSFiddle at http://jsfiddle.net/brianwoelfel/52rrunar/
Here's the callback:
onSelectRow: function(id){
var row = $(this).getLocalRow(id);
if(id && id!==lastsel2){
jQuery('#rowed5').restoreRow(lastsel2);
if(row['securityGroup'] == 'A') {
jQuery('#rowed5').editRow(id,true);
}
lastsel2=id;
}
},
If this method won't work for you, please provide more information about how you're currently doing edits with jqGrid. This example obviously is very trivial and doesn't even post to PHP or mysql or anything.
In case it will be helpful for others, here is how I am implementing Read Only rows in Form Editing mode, based on a column which designates what level of access the user has to each row:
In editoptions, use the beforeShowForm event, like so:
beforeShowForm: function (formid) {
console.log('Checking for READONLY '+formid.name);
var selectedRow = jQuery("#list1").jqGrid('getGridParam','selrow'); //get selected rows
var selRole = $("#list1").jqGrid('getCell', selectedRow, 'ACCROLE');
if(selRole == 'N' || selRole == 'S' || selRole == 'R')
{
//$("<div>Sorry, you do not have access to edit this record.</div>").dialog({title: "Access Denied"});
formid.find("input,select,textarea")
.prop("readonly", "readonly")
.addClass("ui-state-disabled")
.closest(".DataTD")
.prev(".CaptionTD")
.prop("disabled", true)
.addClass("ui-state-disabled");
formid.parent().find('#sData').hide();
var title=$(".ui-jqdialog-title","#edithd"+"list1").html();
title+=' - READONLY VIEW';
$(".ui-jqdialog-title","#edithd"+"list1").html(title);
formid.prepend('<span style="color: Red; font-size: 1em; font-weight: bold;">You viewing READONLY data.</span>');
}

jqGrid row selected but not highlighted

I want to select and unselect a row multiple times by clicking.
My code is so far: (lastSelected is a global var):
beforeSelectRow: function (id)
{
if (lastSelected !== id)
{
grid.setSelection(id);
lastSelected = id;
return;
}
else
{
grid.resetSelection(id);
lastSelected = null;
}
}
The code works fine, but row is highlighted only after first click. The Second click unhighlight it and it keep being unhighlighted when I click it next times, but after 3rd, 5th... clicks it behave like selected (I have modal which pops up when row is selected), but is not highlighted.
Without grid.getSelection(id) it won't highlight at all, but still working like it was selecting and deselecting.
It seems to me that the main error in your code is the returned value of beforeSelectRow. If the returned value in not false then the standard processing will be continued and the row which you previously selected explicitly by usage setSelection can be unselected.
To fix the problem you should return false from beforeSelectRow. Additionally I would suggest to use $(this) instead of grid variable and to use standard selrow parameter of jqGrid instead of usage lastSelected variable. The resulting code could be the following
beforeSelectRow: function (rowid, e) {
var $self = $(this), selectedRowid = $self.jqGrid("getGridParam", "selrow");
if (selectedRowid === rowid) {
$self.jqGrid("resetSelection");
} else {
$self.jqGrid("setSelection", rowid, true, e);
}
return false; // don't process the standard selection
}
The corresponding demo is here.

Kendo AutoComplete - force users to make valid selection

I've got a few Kendo AutoComplete fields linked to remote data (hundreds of possibilities, so DropDownList is not an option).
How can I force users to make a selection from the displayed list?
I'm also retrieving the additional data that's returned from the data source, e.g.
$("#station").kendoAutoComplete({
dataSource: stationData,
minLength: 2,
dataTextField: 'name',
select: function(e){
var dataItem = this.dataItem(e.item.index());
console.dir(dataItem);
}
});
I'm doing additional stuff with the data in dataItem and it needs to be a valid selection.
Thanks
SOLVED:
I think I was possibly over-complicating things. The answer is pretty simple and is posted below.
var valid;
$("#staton").kendoAutoComplete({
minLength: 2,
dataTextField: "name",
open: function(e) {
valid = false;
},
select: function(e){
valid = true;
},
close: function(e){
// if no valid selection - clear input
if (!valid) this.value('');
},
dataSource: datasource
});
This method allows users to type whatever they like into the AutoComplete if list not opens. There are two corrections to fix this:
initialize variable valid as false:
var valid = false;
Check if no valid selection in change event, but not in close:
...
change: function(e){ if (!valid) this.value(''); }
The answer the OP posted, in addition to the answer suggested by #Rock'n'muse are definitely good propositions, but both miss an important and desired functional aspect.
When utilizing the solution given by #Mat and implementing the change-vice-close suggestion from #Rock'n'muse, the typed-in value indeed clears from the widget if no selection is made from the filtered data source. This is great; however, if the user types in something valid and selects a value from the filtered list, then places the cursor at the end of the value and types something which now invalidates the value (doesn't return any valid selections from the data source), the typed-in value is not cleared from the widget.
What's happening is that the isValid value remains true if the previously typed-in (and valid) value should be altered. The solution to this is to set isValid to false as soon as the filtering event is triggered. When the user changes the typed-in value, the widget attempts to filter the data source in search of the typed-in value. Setting isValid to false as soon as the filter event is triggered ensures a "clean slate" for the change event as suggested by the solution from #Rock'n'muse.
Because we're setting isValid to false as soon as the filtering event is triggered, we do not need to do so in the open event (as data source filtering must occur before the user will ever see an option to select). Because of this, the open event binding was removed from #Mat's solution. This also means the initial assignment of false upon declaration of isValid is superfluous, but variable assignment upon declaration is always a good idea.
Below is the solution from #Mat along with the suggestions from #Rock'n'muse and with the filtering implementation applied:
var isValid = false;
$("#staton").kendoAutoComplete({
minLength: 2,
dataTextField: "name",
select: function () {
valid = true;
},
change: function (e) {
// if no valid selection - clear input
if (!valid) {
e.sender.value("");
}
},
filtering: function () {
valid = false;
},
dataSource: datasource
});
As an addendum, using the select event binding to set and evaluate a simple boolean value as #Mat proposes is much cleaner, simpler and faster than using a jQuery $.each(...) on the data source in order to make sure the typed-in value matches an actual item of the data source within the change event. This was my first thought at working a solution before I found the solution from #Mat (this page) and such is my reasoning for up-voting his solution and his question.
Perhaps, can you make your own validation by using the blur event :
$("#station").blur(function() {
var data = stationData,
nbData = data.length,
found = false;
for(var iData = 0; iData < nbData; iData++) {
if(this.value === data[iData].yourfieldname) // replace "yourfieldname" by the corresponding one if needed
found = true;
}
console.log(found);
});
You can check this fiddle.
You most likely need some custom logic which to intercept each key stroke after the min length of two symbols is surpassed, and prevent the option to enter a character which makes the user string not match any of the items from the autocomplete list.
For this purpose intercept the change event of the Kendo autocomplete and compare the current input value from the user against the items from the filtered list.
Hope this helps,
$("#autocomplete_id").val("");
$("#autocomplete").kendoAutoComplete({
dataSource: datasource,
minLength: 1,
dataTextField: "catname",
dataValueField:"id",
select: function(e) {
var dataItem = this.dataItem(e.item.index());
$("#autocomplete_id").val(dataItem.id);
},
dataBound: function(e){
$("#autocomplete_id").val("");
}
});
FYI, autocomplete_id is a hidden field to store the value of the autocomplete. - Sometimes, we would like to have the dataValueField other than dataTextField. So, it serves its purpose.
In this you can get the value of the autocomplete "id" from the element autocomplete_id - which is dataValueField from serverside.
In databound, its values is set to null, and on select, it is assigned the "id" value.
Although the accepted answer works, it is not the best solution.
The solution provided doesn't take into account if the user enters a value before even the kendo AutoComplete widget triggers the open event. In result, the value entered is not forced and therefore, the entry/selection is invalid.
My approach assumes that the application is running in MVC and the array is passed in ViewData. But this can be changed to suit your environment.
My approach:
var validSelect, isSelected;
$("#staton").kendoAutoComplete({
minLength: 2,
filter: "startswith",
dataTextField: "name",
filtering: function(e) {
validSelect = false;
dataArr = #Html.Raw(Json.Encode(ViewData["allStatons"]));
// for loop within the ViewData array to find for matching ID
for (var i = 0; i < dataArr .length; i++){
if (dataArr[i].ID.toString().match("^" + $("#staton").val())) {
validSelect = true;
break;
}
}
// if value entered was not found in array - clear input
if (!validSelect) $("#staton").val("");
},
select: function(e){
isSelected = true;
},
close: function(e){
// if selection is invalid or not selected from the list - clear input
if (!validSelect || !isSelected) $("#staton").val("");
},
dataSource: datasource
});
As you can see, this approach requires the array from the server side on load so that it can match during the filtering event of the widget.
I found this on Telerik's site by just using the change event. For me this works best. I added the "value === ''" check. This will catch when the user "clears" the selection.
Here's the link to the full article.
$("#countries").kendoAutoComplete({
dataSource: data,
filter: "startswith",
placeholder: "Select country...",
change: function() {
var value = this.value();
if (value === '') return;
var found = false;
var data = this.dataSource.view();
for(var idx = 0, length = data.length; idx < length; idx++) {
if (data[idx] === value) {
found = true;
break;
}
}
if (!found) {
this.value("");
alert("Custom values are not allowed");
}
}
});
In my AutoComplete Change event I check for a selected item and clear the cell if not selected.
function myAutoComplete_OnChange(e)
{
if (this.dataItem())
{
// Don't use filtered value as display, instead use this value.
e.sender.element[0].value = this.dataItem().WidgetNumber;
}
else
{
var grid = $("#grid").data("kendoGrid");
grid.dataItems()[grid.select().index()].WidgetKey = null;
grid.dataItems()[grid.select().index()].WidgetNumber = null;
}
}

JQGrid setCell customFormatter

I'm using setCell to set the value of a cell. The problem is it is still calling the customFormatter specified for the column. Is there anyway I can set the value of this cell without it having to go through the customFormatter?
First of all the custom formatter will be used on every grid refresh, so to set the cell value you have to do this after the custom formatter. The best place to do this is inside of loadComplete or gridComplete event handler.
To set the cell value you can use jQuery.text for example. So you should get jQuery object which represent the cell (<td> element) and then use jQuery.text or jQuery.html to change the cell contain. How I understand you, you knows the rowid of the cell and the column name which you want to change. The following code could be:
loadComplete: function() {
var rowid = '2', colName = 'ship_via', tr,
cm = this.p.colModel, iCol = 0, cCol = cm.length;
for (; iCol<cCol; iCol++) {
if (cm[iCol].name === colName) {
// the column found
tr = this.rows.namedItem(rowid);
if (tr) {
// if the row with the rowid there are on the page
$(tr.cells[iCol]).text('Bla Bla');
}
break;
}
}
}
See the corresponding demo here.

Resources