jqGrid : searchrules in single Field searching - jqgrid

I'm trying to validate the search field for integer data alone but unfortunately am unable to do so. I have tried all possible solutions like searchrules:{required:true,integer=true} etc..
But none of them proves fruitful.
I basically launch the search dialog with the field and without inputting any data, am hitting on the 'Find' button. As per the above options, i believe a validation message should be shown to the user asking him to enter a value in the field before hitting find.
[UPDATED] - Code Snippet
var grid = $("#list");
grid.jqGrid({
url:'/index.jsp',
datatype: 'json',
mtype: 'POST',
colNames:['Name','Age', 'Address'],
colModel :[
{name:'name', index:'name', width:55,search:true },
{name:'age', index:'age',
width:90,editable:true,search:true, stype:'text',
searchrules:{required:true,integer:true}},
{name:'address', index:'address', width:80,
align:'right', editable: true,search:false }
],
pager: '#pager',
jsonReader : {
root:"address",
page: "page",
total: "total",
records: "records",
repeatitems: false
},
rowNum:10,
rowList:[10,20,30],
sortname: 'name',
sortorder: 'desc',
viewrecords: true,
gridview: true,
autowidth: true,
toppager: true,
loadtext: "Loading records.....",
caption: 'Test Grid',
gridComplete: function(){
}
});
**grid**.jqGrid('navGrid','#pager',
{view:true,edit:true,add:true,del:true,refresh:true,
refreshtext:'Refresh',addtext:'Add',
edittext:'Edit',cloneToTop:true,
edittitle: "Edit selected row"},
{},{},{},
{caption: "Search The Grid",Find: "Find Value",Reset: "Reset"},
{});
[Updated] : Am not able to make the searchrules properly work for the single/advanced searching modes.
[Updated] : Even the 'Validation in Search' in
jqGrid Demo is not working for searchrules.

The reason of described problem is a bug in jqGrid. The line
ret = $.jgrid.checkValues(val, -1, null, colModelItem.searchrules, colModelItem.label);
initialize the third parameter of $.jgrid.checkValues to null, but the last version of checkValues implementation started (see the line) with
var cm = g.p.colModel;
but g is initialized to null. The last modification which generates the error was based on my suggestion, but I don't wrote the part of the code.
One can solve the problem in different way. I would suggest to modify the line where $.jgrid.checkValues will be called with null parameter to the following
ret = $.jgrid.checkValues(val, -1, {p: {colModel: p.columns}}, colModelItem.searchrules, colModelItem.label);
Additionally, to be sure, I would suggest to modify one more line
if(!nm) { nm = g.p.colNames[valref]; }
to
if(!nm) { nm = g.p.colNames != null ? g.p.colNames[valref] : cm.label; }
The fixed version of jquery.jqGrid.src.js one can get here. I will post my bug report with the same suggestions later ti trirand.

Related

passing csrf token through jqgrid on cell edit

I'm using Codeigniter and jqgrid to build an application. I've recently enabled Codeigniter's builtin CSRF protection for security reasons, and it broke some stuff with jqgrid. I've been able to pass the csrf token when jqgrid is instantiated so all my data loads (by adding the csrf token to the postData), but now anytime I edit a cell I get a 500 error because the csrf token isn't being passed. I can verify this by looking at the post data each time I edit a cell. I read several places that editData is what I want, but adding the token in there doesn't seem to pass it in the edit ajax request. Any ideas?
$("#cust_grid").jqGrid({
url:'/ajax/grid',
datatype: 'xml',
mtype: 'POST',
postData: {<?php echo $this->security->get_csrf_token_name().":'".$this->security->get_csrf_hash()."'"; ?>},
editData: {<?php echo $this->security->get_csrf_token_name().":'".$this->security->get_csrf_hash()."'"; ?>},
colNames:['Name1', 'Name2'],
colModel :[
{name:'name1', index:'name1', width:55, search: true},
{name:'name2', index:'name2', width:110, search: true},
],
pager: '#pager',
rowNum:25,
rowList:[10,25,50,100],
sortname: 'name1',
sortorder: 'asc',
viewrecords: true,
gridview: true,
caption: 'Customers',
height: 600,
width: 1200,
shrinkToFit: false,
altRows: true,
cellEdit: true,
cellsubmit: "remote",
cellurl: "/ajax/editCell",
},
{}
);
It seems that you can solve the problem mostly in the same way like I described here. The main difference is that you use cell editing instead of form editing. So you should use ajaxCellOptions instead of ajaxEditOptions:
ajaxCellOptions: {
loadBeforeSend: function(jqXHR) {
// you should modify the next line to get the CSRF tocken
// in any way (for example $('meta[name=csrf]').attr('content')
// if you have <meta name="csrf" content="abcdefjklmnopqrstuvwxyz="/>)
var csrf_token = '<%= token_value %>'; // any way to get
jqXHR.setRequestHeader('X-CSRF-Token', csrf_token);
}
}
I ended up finding another solution to the problem. I was investigating the cell editing link posted in the another answer and I saw the beforeSubmitCell option. Turns out if you return json data from that function it will be appended to the post data each time a cell is edited. So all I needed to do was add as an option:
beforeSubmitCell: function (rowid,celname,value,iRow,iCol) {
return {<?php echo $this->security->get_csrf_token_name().":'".$this->security->get_csrf_hash()."'";?>}
},
No answer working out after I tried. Then i found the solution for passing CSRF Token from Jqgrid inline editing to Django by using this :
onSelectRow: function(id){
if(id && id!==lastSel){
$(selector).restoreRow(lastSel);
lastSel=id;
}
var editparameters = {
extraparam: {csrfmiddlewaretoken: $('.token-data').data('token')},
keys: true,
};
$(selector).jqGrid('editRow', id, editparameters);
}
Example usage :
http://yodi.polatic.me/jqgrid-inline-editing-integration-with-django-send-csrf-token/

jqGrid - Setting select value in edit form

I'm having a hard time trying to set the value of a select box in the edit form. For example I have my colModel set up like this.
colModel:[
{name:'communication_id', key: true, index:'communication_id', width:30},
{name:'communication_type_id', index:'communication_type_id', width:30},
{name:'communication_type_select',index:'communication_type_select',hidden:true,width:150, editable:true,edittype:'select',formatter:'select',editrules: {edithidden:true},
formoptions:{label:'Communication Type'},
editoptions:{dataUrl:"working_data_url",
buildSelect: function(json){
var response = $.parseJSON(json);
var s = '<select>';
$.each(response.results,function(i,com){
s += ('<option value="' + com.communication_type_id + '">'+ com.communication_type_desc + '</option>');
});
return s + "</select>";
},dataInit: function(elem){
alert(temp);
//alert($('#com_table_communication_type_id').val());
//$(elem).val($('#com_table_communication_type_id').val());
}}},
{name:'communication_send_dt', index:'communication_send_dt', width:150, sortable:true, sorttype: 'date',
firstsortorder: 'desc', datefmt:'m/d/Y', editable:true},
editoptions: {recreateForm:true},
rowNum:10,
width:'100%',
rowList:[10,20,30],
pager: '#com_pager',
sortname: 'communication_send_dt',
viewrecords: true,
sortorder: "desc",
loadonce:true,
caption: "Communication",
jsonReader: {
repeatitems : false,
root: "results"
},
height: '100%',
onSelectRow: function(communication_id){
var comtype = $(this).getRowData(communication_id);
var temp = comtype['communication_type_id'];
}
});
grid.jqGrid('navGrid','#com_pager',{edit:true,add:false,del:false});
When I click the edit button it loads the select options correctly, but I am having trouble with which one is selected. I want the value from communication_type_id to load into communication_type_select and I have tried different things to get that too happen. Basically if the id in communication_type_id is 2, then I want the select box in the edit form to be set to 2 as well when the edit form loads. Any help on this?
Update 1: I got it mostly working now by using beforeShowForm, but now I am running into a weird thing. When I have an alert in the beforeShowForm everything works, but when its commented out, it does not work! Thanks for your help #Oleg!
grid.jqGrid('navGrid','#com_pager',{edit:true,add:false,del:false},
{closeOnEscape:true, recreateForm:true,beforeShowForm: function(formid){
//alert("com type id = "+comidvar + " response id = "+comrespvar + " com form type id = "+comfrmtypevar);
$("#communication_type_select", formid).attr("value",comidvar);
$("#form_response_select", formid).attr("value",comrespvar);
$("#form_type_select", formid).attr("value", comfrmtypevar);
}},
If I understand you correct you should use ajaxSelectOptions option of jqGrid with data property. You can define some additional option like communication_type_id in the data which value you can returns by the usage of $("#list").jqGrid('getGridParam', 'selrow') and then getCell to get the value from communication_type_id column. See the answer for details.

jqGrid getCell method returning undefined in IE8

While using jqGrid's getCell method, it always returns me undefined in IE8. On Mozilla it works fine.
$('#grid').jqGrid('getCell',id,column); //returns undefined in IE8 :(
Should I use the method defined in this answer instead.
function getCellValue(rowId, cellId) {
var cell = jQuery('#' + rowId + '_' + cellId);
var val = cell.val();
return val;
}
What is the best approach?
I have treegrid implemented and am using version 4.3.1 of jqGrid.
My configurations is
var grid = $("#grid").jqGrid({
treeGrid: true,
treeGridModel: 'adjacency',
ExpandColumn: 'businessAreaName',
ExpandColClick : true,
url:'agileProgramme/records.do',
datatype: 'json',
mtype: 'GET',
colNames:['Id'
, 'Business Area'
, 'Investment'
, 'Org'
, 'Goal'
],
colModel:[
/*00*/ {name:'agileProgrammeId',index:'agileProgrammeId', width:0, editable:false,hidden:true},
/*01*/ {name:'businessAreaName',index:'businessAreaName', width:160, editable:false},
/*02*/ {name:'programmeName',index:'programmeName', width:150, editable:false, classes:'link'},
/*03*/ {name:'org',index:'org', width:50, editable:false, classes:'orgHierarchy', sortable : false},
/*04*/ {name:'goal',index:'goal', width:70, editable:false}
],
treeReader : {
level_field: "level",
parent_id_field: "parent",
leaf_field: "leaf",
expanded_field: "expanded"
},
autowidth: true,
height: 240,
pager: '#pager',
sortname: 'id',
sortorder: "asc",
toolbar:[true,"top"],
caption:"TableGridDemo",
emptyrecords: "Empty records",
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "cell",
id: "agileProgrammeId"
}
});
Thanks Oleg for the response. I found the root cause of the problem. It is in the $.unformat method of jqGrid.
return ret !== undefined ? ret : cnt===true ? $(cellval).text() : $.jgrid.htmlDecode($(cellval).html());
I changed it to
return (typeof ret != 'undefined') ? ret : cnt===true ? $(cellval).text() : $.jgrid.htmlDecode($(cellval).html());
Actually the ret !== undefined is not working in ie8. Once, I changed it to typeof ret != 'undefined', it worked like expected.
I supposed that you used getCell in the wrong place. The most safe place to use getCell in in loadComplete or inside of some other callback. In case situation you are sure that the data which you try to read are already in jqGrid. IE8 is much slowly as other web browsers so I can only suppose that even you used getCell in the wrong place the modern browsers are already read the grid contain and so your tests were successful.
The demo I made based on the code which you previously posted. It read 'programmeName' from the first loaded row with respect of getCell and display it with respect of alert. How you can verify the code works without any problem in IE8.

customize: POST output in jqGrid without changing source file?

I'm trying to turn jqGrid within MODx, as do other data exchange using "$. ajax", move the call from a URL to a resource protected by a password and from there call a snippet of code in PHP, so the security framework, the ajax call is guaranteed
This is one example of a chunk $.ajax:
$.ajax ({
url :'[[~94]]',
type: 'post',
async: false,
success: function(rsp) {
$.Cookie("xxxxxx-tipodirlist", rsp);
}
});
*[[~94]] is a protected resource is within a snippet call [[!SnpBridgedata_blabla]]
the system works perfectly well throughout the web application, receiving and sending data safely and securely.
Now a customer asked me for a completed application wanted web results in a good grid and after seeing a bit of code I decided to use jqGrid for my project.
integration was quick and I am very happy to have changed "DataTable" with "jqGrid," but when I finished the test, change the absolute path to xxxxxx.php with the call to snippet
this is the code for jqGrid:
chargeSedi function (idx)
{
// Test with file. Php !work fine!
// Var esURL = 'http://xxxxx.com/xxxxxxx.php?IDX =' + idx;
// Test with MODx resource !not work!
esURL var = '[[~ 97]] & IDX =' + idx;
csURL var = '[[~ 96]] & IDX =' + idx;
tipodirlist = $ var. cookie ("xxxxxxxx-tipodirlist");
tiposedelist = $ var. cookie ("xxxxxxx-tiposedelist");
$("#sediTable").ready(function() {
$("#sediTable").jqGrid({
url:csURL,
datatype: "json",
height: 250,
autowidth:true,
colNames:[ 'ID','CODICE', 'NOME','TDIR', 'DIR','COMUNE', 'PROVINCIA','CAP', 'TSEDE','NOTA'],
colModel:[
{name:'ID',index:'ID', width:25, editable: false},
{name:'CODICE',index:'CODICE', width:60, editable: true},
{name:'NOME',index:'NOME', width:60, editable: true},
{name:'TDIR',index:'TDIR', width:60, editable: true,edittype:"select",editoptions:{value:tipodirlist}},
{name:'DIR',index:'DIR', width:200, sortable:false,editable: true},
{name:'COMUNE',index:'COMUNE', width:170, sortable:false,editable: true},
{name:'PROVINCIA',index:'PROVINCIA', width:170, sortable:false,editable: true},
{name:'CAP',index:'CAP', width:40, sortable:false,editable: true},
{name:'TSEDE',index:'TSEDE', width:90, editable: true,edittype:"select",editoptions:{value:tiposedelist}},
{name:'NOTA',index:'NOTA', width:170, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"10"}} ],
sortname: 'ID',
viewrecords: true,
sortorder: "desc",
loadonce: true,
editurl: esURL ,
caption: "Sedi" });
});
]
and for my surprise the MODx deny Access to jqGrid ajax calls, as if you were out of session, but after hours testing and watching the traffic with wireshark I realized that jqGrid sends a POST variable called "id" and call MODx a GET variable "id". this in other environments is possible without problem, but it is not possible MODx and there's the problem.
my question is how I can change the name of the POST variable "id" jqGrid, without changing the source of jqGrid?
at the same time wanted to ask, you can customize the import of a select the value and not the index
example of trame POST:
{Name: 'TDIR', index: 'TDIR', width: 60, editable: true, EditType: "select" editoptions: {value: tipodirlist}}
tipodirlist = 1:via;2:piazza;3:ect
TDIR=2
CODICE=1&NOME=principale&TDIR=2&DIR=Roma&COMUNE=Torino&PROVINCIA=Torino&CAP=10000&TSEDE=2&NOTA=NO=edit&id=0
for this:
TDIR=piazza
CODICE=1&NOME=principale&TDIR=piazza&DIR=Roma&COMUNE=Torino&PROVINCIA=Torino&CAP=10000&TSEDE=2&NOTA=NO=edit&id=0
without having to filter the results on the server.
I hope I've explained well and clear. as I asked myself, the team "StackOverflow" before asking this question
Thank you so much
Regards
niro.
PS.I hope that GOD "Oleg" help me:)
I don't know and don't use MODx. Nevertheless I hope that your problem is: how to rename the name of the id parameter to have no conflict with the id parameter used by MODx.
If I understand your question correct you should just add additional prmNames parameter which set the new name of id parameter used in editing operations:
prmNames: {id: 'myId'}
The example will rename the default id parameter name ({id: "id"}) to myId which you should you in your server part.

Fire an event after a local delete jqgrid

So what I am trying to do is fire an event AFTER a local delete has been done on the jqgrid. The reason for this is because I am dealing with a global save on the website so I am not posting directly to the server. I am storing the data in JSON form within a hidden element on the page so when the user finally saves the element value is grabbed and sent to the server along with all the other data.
The issue I am having is that when I delete a row from the jqgrid I am not able to update the hidden element with the change, so if the user saves after that it is like the remove never happened.
$("#translationMappingGrid").jqGrid({
data: mydata,
datatype: "local",
mtype: 'GET',
colNames:['From','To', 'Type'],
colModel :[
{name:'from',index:'from', width:180, align:"left",sorttype:"float", editable: true, editrules:{custom:true, custom_func:validateIPGridInput}},
{name:'to',index:'to', width:180, align:"left",sorttype:"float", editable: true, editrules:{custom:true, custom_func:validateIPGridInput}},
{name:'type',index:'type', width:200,align:"left",sorttype:"float", editable: true,
edittype:"select", formatter:'select', editoptions:{
value:"0:Never Translate;1:Always Translate;2:Only If Source;3:Only If Destination"}
},
],
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'invid',
sortorder: 'desc',
viewrecords: true,
gridview: true,
caption: 'Mapping',
editurl: 'probe.sysinfo.ajax',
url:'clientArray',
onSelectRow: function(id){
jQuery('#translationMappingGrid').jqGrid('restoreRow',lastsel2);
//below are the parameters for edit row, the function is called after a successful edit has been done
//jQuery("#grid_id").jqGrid('editRow',rowid, keys, oneditfunc, succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc);
jQuery('#translationMappingGrid').jqGrid('editRow',id,true,"","","","",function () {
setTranslationMappingJSON(getGridDataJSONString(this));
window.parent.document.getElementById('notificationDiv').style.display= "";
});
lastsel2=id;
},
afterInsertRow: function(rowid, rowdata, rowelem ){
//alert("after insert row");
setTranslationMappingJSON(getGridDataJSONString(this));
window.parent.document.getElementById('notificationDiv').style.display= "";
}
});
//adds buttons to jqgrid nav bar
jQuery("#translationMappingGrid").navGrid('#pager',{
edit:false,add:true,del:true,search:false,refresh:true
}, {
closeAfterAdd:true,
closeAfterEdit: true
},
{
closeAfterAdd:true,
closeAfterEdit: true,
afterSubmit: function(response, postdata) {
alert("after complete row");
setTranslationMappingJSON(getGridDataJSONString(this));
window.parent.document.getElementById('notificationDiv').style.display= "";
return [true,""];
}
});
As indicated in the code above I am successfully updating the hidden element with the changes on both add and edit (inline) via afterrestorefunc, but this is not working for delete.
I have tried using afterSubmit in the code above, but this is not working either. I have been working on this for a few days now and have come to the conclusion that I might have to write my own custom code for the delete button entirely, but I am hoping this is not the case.
The OP wrote in an edit:
So it appears as though I was staring at the issue for too long and was missing the obvious....lucky me. I found out two things:
Using afterSubmit was the wrong thing to use, instead I should be using afterComplete.
I had tried using afterComplete before trying afterSubmit and the reason it was not working it because I am putting them both within the "add" parameters and NOT the delete. Once again, I feel pretty awesome for that one :)
Well now that I have figured that out here is the code snippet that saved my life:
jQuery("#translationMappingGrid").navGrid('#pager',{
edit:false,add:true,del:true,search:false,refresh:true
}, {
closeAfterAdd:true,
closeAfterEdit: true
},
{
closeAfterAdd:true,
closeAfterEdit: true
},{
afterComplete:
function () {
//saves the changed JSON string to the hidden element
setTranslationMappingJSON(getGridDataJSONString(jQuery('#translationMappingGrid')));
window.parent.document.getElementById('notificationDiv').style.display= "";
}
});
This is tested and the function is called after the delete has been performed and saves the local changes to my hidden element.
For anyone who is curious about what the format is:
/* The following is the setup
navGrid(<name>, {<buttons, true/false},
{
<edit parameters>
},
{
<add parameters>
},
{
<delete parameters>
}
*/
Thanks for everyone who might have started working on this, and definitely thanks to the developers of jqgrid. Best javascript grid I have ever worked with!

Resources