jqgrid: how to send search operator information to server side - jqgrid

I have setup grid instance something like this:
$("#list").jqGrid({
url:'rest/usertest/users',
datatype: "json",
mtype: "POST",
colNames: ["Username", "Name", "Grouping"],
colModel: [
{ name: "username" },
{ name: "name", width: 90 },
{ name: "grouping", width: 80, sorttype:'string',searchoptions:{sopt:['eq','bw','bn','cn','nc','ew','en']}},
],
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
sortname: "username",
sortorder: "asc",
viewrecords: true,
multiselect: false,
autowidth: true,
height: 'auto',
gridview: true,
multiSort: true
});
jQuery("#list").jqGrid('filterToolbar',{searchOnEnter : false,searchOperators : true});
I am trying to do a server side operand based search via grid. The problem is that it doesn't send any information about the chosen operator to the server-side. The request does not contain any information about the selected operator (eq, bw, bn etc).
I am trying to do so with the toolbar search itself. Am I missing any configuration parameter? Please advice.
EDIT:
I tried the answer given below by #Tomcat, however it still does not work. The search is successful but I am not able to the make the operand based search work on server side.
As in the pic below, there is not info about the chosen operand.

Having stringResult : true is necessary.
$('#list').filterToolbar({
groupOp: 'OR',
defaultSearch: "cn",
autosearch: true,
searchOnEnter: true,
searchOperators: true, // activates the operators menu
stringResult : true // activates multi-field search
});

Try to add to the grid setup next properties:
searchOperators: true,
search: true,
After that request to the server should contain the next parameters:
"filters" - search filter,
"sidx" -filed for sorting,
"sord" - sorting order ('asc' or 'desc'), '_search' - bool trigger for searching.
Ok, please take a look at this code, it works and send all the necessary information. Pay attention to the jQuery("#list").jqGrid('filterToolbar', { properties.
jQuery("#list").jqGrid('filterToolbar', {
searchOnEnter: false,
searchOperators: true,
multipleSearch: true,
stringResult: true,
groupOps: [{ op: "AND", text: "all" }, { op: "OR", text: "any" }],
defaultSearch: 'cn', ignoreCase: true
});
Hope it will be helpful.

Related

JqGrid - Set Default Operand For a Column

Is it possible to set a default search operand for a single column? The column is called "Severity" and has default value of 4. I would like to display "le" and by default filter values that are less or equal to this value.
Here is a snippet from the code:
jQuery(document).ready(function() {
jQuery('#grid').jqGrid({
url:'logging.ajax',
datatype: 'json',
colModel:[
{name:'Code', index:'Code', width:100, sorttype:'int', searchoptions:{sopt:['eq','cn','ne','nc','lt','le','gt','ge','bw','bn','in','ni','ew','en']}},
{name:'Severity', index:'Severity', width:100, sorttype:'int', searchoptions:{defaultValue: 4, sopt:['eq','cn','ne','nc','lt','le','gt','ge','bw','bn','in','ni','ew','en']}},
{name:'Log', index:'Log', align: 'left', width:200, searchoptions:{sopt:['eq','cn','ne','nc','bw','bn','in','ni','ew','en']}},
{name:'ID', index:'ID', width: 100, sorttype:'int', key: true, searchoptions:{sopt:['eq','cn','ne','nc','lt','le','gt','ge','bw','bn','in','ni','ew','en']}}
],
rowNum: 500,
rowList: [100,200,500,1000],
styleUI : 'Bootstrap',
gridview: true,
pager: '#gridpagernav',
sortname: 'ID',
loadonce: false,
viewrecords: true,
cellEdit: false,
sortorder: 'desc',
multiSort: true,
ExpandColClick: true,
forceFit: true,
editurl:'logging.ajax',
autowidth: true,
shrinkToFit: false,
height: Math.max(200, $(window).height()-400)
}).navGrid('#gridpagernav',
{
edit: false,
add: false,
del: false,
refresh: true,
search: true,
recreateForm: true
}, //options
{
}, // edit options
{
}, // add options
{
}, // del options
{
closeAfterSearch: true,
multipleSearch: true,
multipleGroup: true,
showQuery: false,
} // search options
).filterToolbar({stringResult: true, searchOnEnter: false, defaultSearch: 'cn', ignoreCase: true, searchOperators: true});
I commonly use the following trick to display different operand in the search toolbar. It works fine for "cn".
$('.soptclass[colname=\"Severity\"]').attr('soper', 'le')
$('.soptclass[colname=\"Severity\"]').html('<=')
$('.soptclass[colname=\"Log\"]').attr('soper', 'cn')
$('.soptclass[colname=\"Log\"]').html('~')
When I add the following line of code, it automatically uses the right filtering on load and when I play around with other columns, it always uses the correct filter.
postData: { filters:JSON.stringify({'rules': [{'field':'Severity', 'op':'le', 'data':'4'}]}) },
However, when I press refresh button, filtering is reset to "eq".
What I would like to achieve is that either "le" on the column "Severity" is always enforced or to somehow fix the refresh button so it modifies filter's "op".
Cheers.
By default first option in sopt array is defaul. To do what you want set it like this
colModel:[
...
{name:'Severity', index:'Severity', width:100, sorttype:'int', searchoptions:{defaultValue: 4, sopt:['le','eq','cn','ne','nc','lt','gt','ge','bw','bn','in','ni','ew','en']}},
...
],
and you can delete the code which change the the 'le' to default one.
I resolved it by adding custom navigation button that replaces refresh button. Solution is:
jQuery(document).ready(function() {
jQuery('#grid').jqGrid({
url:'logging.ajax',
datatype: 'json',
postData: { filters:JSON.stringify({'rules': [{'field':'Severity', 'op':'le', 'data':'4'}]}) },
colModel:[
{name:'Code', index:'Code', width:100, sorttype:'int', searchoptions:{sopt:['eq','cn','ne','nc','lt','le','gt','ge','bw','bn','in','ni','ew','en']}},
{name:'Severity', index:'Severity', width:100, sorttype:'int', searchoptions:{defaultValue: 4, sopt:['eq','cn','ne','nc','lt','le','gt','ge','bw','bn','in','ni','ew','en']}},
{name:'Log', index:'Log', align: 'left', width:200, searchoptions:{sopt:['eq','cn','ne','nc','bw','bn','in','ni','ew','en']}},
{name:'ID', index:'ID', width: 100, sorttype:'int', key: true, searchoptions:{sopt:['eq','cn','ne','nc','lt','le','gt','ge','bw','bn','in','ni','ew','en']}}
],
rowNum: 500,
rowList: [100,200,500,1000],
styleUI : 'Bootstrap',
gridview: true,
pager: '#gridpagernav',
sortname: 'ID',
loadonce: false,
viewrecords: true,
cellEdit: false,
sortorder: 'desc',
multiSort: true,
ExpandColClick: true,
forceFit: true,
editurl:'logging.ajax',
autowidth: true,
shrinkToFit: false,
height: Math.max(200, $(window).height()-400)
}).navGrid('#gridpagernav',
{
edit: false,
add: false,
del: false,
refresh: false,
search: true,
recreateForm: true
}, //options
{
}, // edit options
{
}, // add options
{
}, // del options
{
closeAfterSearch: true,
multipleSearch: true,
multipleGroup: true,
showQuery: false,
} // search options
).filterToolbar({stringResult: true, searchOnEnter: false, defaultSearch: 'cn', ignoreCase: true, searchOperators: true});
I have added postData line and changed "refresh" from true to false, which removes the native refresh button. I have added following new code:
$('#grid').navButtonAdd('#gridpagernav',{
caption: '',
buttonicon: 'glyphicon-refresh',
onClickButton: function() {
var postData = $('#grid').jqGrid('getGridParam','postData');
if ((postData) && (postData.filters)) {
var filters = JSON.parse(postData.filters);
if (filters.rules) {
var rowsCount = filters.rules.length;
var i;
for (i = 0; i < rowsCount; i++) {
if (filters.rules[i].field) {
$('#gs_' + filters.rules[i].field).val('');
}
}
}
}
$('.soptclass[colname=\"Severity\"]').attr('soper', 'le')
$('.soptclass[colname=\"Severity\"]').html('<=')
$('#gs_Severity').val('4');
$('#grid').setGridParam({ postData: { filters:JSON.stringify({'rules': [{'field':'Severity', 'op':'le', 'data':'4'}]}) } });
$('#grid').trigger('reloadGrid');
},
});
This creates a new navigation button and places it as the last button. As I am using bootstrap UI, I have to use glyphicon icons. When user presses the button, it removes any filled out values in the top filtering/search toolbar and puts back Severity value 4 and operand. It sets the filtering back and triggers reloadGrid.
I am also still using this code, so that it changes visually operand at the grid load:
$('.soptclass[colname=\"Severity\"]').attr('soper', 'le')
$('.soptclass[colname=\"Severity\"]').html('<=')

How to perform toolbar searching based on certain condition in free jqgrid 4.15.4

Though I have spent a lot of time on looking for similar QA here but Can't able to find out. If You think that I missed checking something please let me know.
question metadata:
So I am using free jqGrid 4.15.4 for showing data in view. I am able to do all things with awesome documentation. but one certain condition where I am not getting about steps.
In my grid, I have 4 columns named as Id, Name, Group, and Status. Group(Section A/ Section B....) are coming from database. Status(New/Pass /Fail) column consist dropdown and by default value is "New" for all records.
question statement :
There are 5 records and I have Selected "Pass" status for 2 out of 5. Now I want to see all 5 records if I select "New" in filter toolbar for that particular group(section A). Since I don't how many names belongs to that particular group, so I want to check this by filtering all records with "New" status. Is this possible with jqgrid? StudentGrid.png
Here is the code snippet:
$("#grid").jqGrid({
url: '/StudentsView/GetAllData',
mtype: "GET",
datatype: "json",
colNames: ['Id','Name', 'Group','Status'],
colModel: [
{label: "Id",name: 'Id',hidden: true,search: false,key:true},
{label: "Name",name: 'Name', search: true, stype: 'text'},
{label: "GroupNo",name: 'GroupNo',searchoptions: {searchOperators: true,sopt: ['eq', 'cn', 'nc'] }, search: true, multipleSearch: true, multipleGroup:true},
{
label: "Status",
name: 'Status',
cellEdit: true,
edittype: 'select',
editable: true,
editoptions: {
value: getStatusOptions(),
dataEvents: [{
type: 'change',
fn: function (e) {
if (statusid != 0)
{
ChangeStatus(row.Id, row.Name, row.Group, statusid);
}
}
}],
}
}
pager: jQuery('#pager'),
loadonce: true,
viewrecords: true,
gridview: true,
iconSet: "fontAwesome",
emptyrecords: "No records to display",
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "Id"
}
});
$('#grid').jqGrid('filterToolbar', { stringResult: true,searchOnEnter:false, defaultSearch: "cn", multipleSearch: true, searchOperators: true,
search: true, loadFilterDefaults: true });
$('#grid').jqGrid('navGrid', "#pager", {
search: false, // show search button on the toolbar
add: false,
edit: false,
del: false,
refresh: true
});
I have added a diagram for better understanding. Thanks in Advance.

Jqgrid: Grid refresh on edit, paging

Using latest version of free jqgrid.
I am using the below code for my jqgrid.
I have some issues and question:
1) When I go to next page and previous page not sure what happens but my grid items keep moving up and down.
2) When I add/edit an item for form field I want the grid to refresh and get updated from the server but this does not happens and again my newly added data is lost in the grid as mentioned in my point1. I tried to add navOptions: { reloadGridOptions: { fromServer: true } } but still nothing.
3) When the user clicks on edit button on my pager it opens the user form field. I want the submit button to show edit instead of "Add" which it shows currently.
Here is my code below:
<script type="text/javascript">
$(function () {
"use strict";
var $grid = $("#list");
$grid.jqGrid({
url: '#Url.Action("GetData", "Home")',
datatype: "json",
mtype: 'Get',
colNames: ['Id', 'Name', 'Sex', 'Address'],
loadonce: true,
height: '100%',
autowidth: true,
emptyrecords: "No Users found.",
colModel: [
{ name: 'empid', index: 'empid', editable: true, editrules: { required: true}},
{ name: 'fname', index: 'fname', editable: true, editrules: { required: true}}, //currently these are texbox, but I want this to be label which gets filled based on the empid
{ name: 'lname', index: 'lname', editable: true, editrules: { required: true}},
{ name: 'address', index: 'address', editable: true, editrules: { required: true}}
],
cmTemplate: { autoResizable: true, editable: true },
autoResizing: { compact: true, resetWidthOrg: true },
iconSet: "fontAwesome",
guiStyle: "bootstrap",
rowNum: 10,
rowList: [5, 10, 20, "10000:All"],
viewrecords: true,
autoencode: true,
sortable: true,
pager: true,
rownumbers: true,
sortname: "empid",
sortorder: "desc",
pagerRightWidth: 150,
inlineEditing: {
keys: true
},
searching: {
loadFilterDefaults: false,
closeOnEscape: true,
searchOperators: true,
searchOnEnter: true,
caption: "Search",
Find: "Search"
},
editurl:'#Url.Action("GetDetails", "Home")',
formEditing: {
reloadGridOptions: { fromServer: true },
reloadAfterSubmit: true,
width: 460,
closeOnEscape: true,
closeAfterEdit: true,
closeAfterAdd: true,
closeAfterDelete: true,
savekey: [true, 13],
addCaption: "Add",
editCaption: "Edit",
bSubmit: "Add"
},
formDeleting: {
width: 320,
caption: 'Delete'
},
navOptions: { reloadGridOptions: { fromServer: true } }
}).jqGrid("navGrid")
.editGridRow("new", properties);
});
</script>
The first two items above I was able to resolve using below code:
navOptions: { reloadGridOptions: { fromServer: true } }
But the 3rd item I am still not able to resolve where I am not able to change the text of the Add button to change it to edit when the edit toolbar button is clicked

Why "allData" is an empty array?

I am trying to get the data from a jqGrid (free version and latest version) and it's suppose that I get:
all the data if none is selected
the selected data if any
This is how I am doing it:
$(function () {
var $order_logs = $('#order_logs');
$order_logs.jqGrid({
url: Routing.generate('api_order_logs'),
datatype: "json",
colModel: $colmodel.data('values'),
width: 980,
height: 300,
pager: true,
toppager: true,
hoverrows: true,
shrinkToFit: true,
autowidth: true,
rownumbers: true,
viewrecords: true,
rowList: [25, 50, 100],
rownumWidth: 60,
gridview: true,
sortable: {
options: {
items: ">th:not(:has(#jqgh_order_logs_cb,#jqgh_order_logs_rn,#jqgh_order_logs_actions),:hidden)"
}
},
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
records: 'records',
cell: '',
repeatitems: false
},
cmTemplate: {autoResizable: true, editable: true},
autoResizing: {compact: true, resetWidthOrg: true},
autoresizeOnLoad: true
}).jqGrid('navGrid', {
edit: false,
add: false,
del: false,
search: false,
refresh: true,
refreshstate: "current",
cloneToTop: true
}).jqGrid('navButtonAdd', {
caption: 'Export',
title: 'Export',
onClickButton: function () {
var filteredData = $order_logs.jqGrid("getGridParam").lastSelectedData,
allData = $order_logs.jqGrid('getGridParam', 'data');
exportData(filteredData, allData);
}
});
});
function exportData(filteredData, allData) {
if (filteredData.length === 0 || allData.length === 0) {
alert('There is no data to export');
return;
}
// Export only the filtered data
if (filteredData.length > 0) {
return;
}
// Export all the grid data
}
For some reason the value of allData is always an empty array and I am not sure since I am using the same code as everyone is using out there and found in a lot of answer here in SO.
UPDATE:
Currently the grid is holding six columns and a set of 60 records as total paginated by 20 each time however you can change the pagination to be 50 or 100.
Can any tell me why is this?
I'd recommend to use loadonce: true, forceClientSorting: true options in case of small dataset: less at 1000 or 10000 rows. It simplifies the code server side and you can use full functionality of free jqGrid. The problem with access to lastSelectedData and data will be solved.
More then that, you can easy use many advanced features like createColumnIndex: true, generateValue: true of generateDatalist: true options and so on. See demos included in README of version 4.14.1. Good and comfortable filtering of the data is, in my option, the part of displaying the data. Having the data locally allows to find unique values and build <select> in the filter bar or to use <datalist> to have autocomplete functionality.

JqGrid key:true not working with field having custom formatter

I have a grid with following options where "id" I want to set for a row need to be custom formatted.
There are two columns libCode and matCode.
Combining data of these two I want to create Id for row as follows:-
" ;libCode=[libcode];matCode=[matCode]"
But key=true option is not working with this field having its data set by custom formatter.
It returns the row no. if no xmlmap option is defined, or returns data from xmlmap element from XML response but not what custom formatter sets.
I want to know that why key option is not working and is there any other way I could implement this.
Here is my code for grid:
$(function () {
$("#list").jqGrid({
url: "./TestServlet?operation=RetrieveAll&accept=List",
datatype: "xml",
mtype: "GET",
colNames: ["Lib Code", "Mat Code", "Row Id"],
colModel: [ { name: "libCode", hidden:true, xmlmap:"libCd"},
{ name: "matCode", hidden:true, xmlmap:"matCd"},
{ name: "rowId", formatter:formatName , key:true}
],
xmlReader:{
root:"libs",
row:"lib",
repeatitems: false
},
pager: "#pager",
rowNum: 10,
rownumbers: true,
rowList: [10, 20, 30],
sortname: "libCd",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
loadonce: false,
caption: "Library"
});
});
function formatName(cellValue, options, rowObject)
{
return " ;libCd="+$(rowObject).find('libCd').text()+";matCd="+$(rowObject).find('matCd').text();
}
Set property loadonce to true instead of false i.e. loadonce: true.

Resources