JqGrid - Set Default Operand For a Column - jqgrid

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('<=')

Related

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

jqgrid v5.2.1 with subgrid and local data CRUD operations

Here is my scenario. My jqgrid v5.2.1 doesn't display any data when a page loads up. It is by design. Users will either have to enter all the data for the grid and subgrid manually or click a button to load a default data from the server in the json format via
$("#jqGrid").jqGrid('setGridParam', { datatype: 'local', data: dataResponse.groups }).trigger("reloadGrid");
Users perform CRUD operations locally until the data is right in which case a button is clicked and the grids data goes to the server via $("#jqGrid").jqGrid('getGridParam', 'data').
Edit/Delete operations work fine with the default data loaded but I have a problem with adding new records.
Id's of new rows are always _empty(which is fine because the server side will generated it), but the new rows from the subgrids are not transferred to the server. The question is how to establish the relationship between the newly created rows in the main grid and associated rows in the subgrid and then transfer everything to the server for processing?
Here is the code:
var mainGridPrefix = "s_";
$("#jqGrid").jqGrid({
styleUI: 'Bootstrap',
datatype: 'local',
editurl: 'clientArray',
postData: {},
colNames: ['Id', 'Group', 'Group Description', 'Markets', 'Group sort order'],
colModel: [
{ name: 'id', key: true, hidden: true },
{ name: 'name', width: 300, sortable: false, editable: true, editrules: { required: true }, editoptions: { maxlength: 50 } },
{ name: 'description', width: 700, sortable: false, editable: true, editoptions: { maxlength: 256 } },
{ name: 'market', width: 200, sortable: false, editable: true, editrules: { required: true }, editoptions: { maxlength: 50 } },
{ name: 'sortOrder', width: 130, sortable: false, editable: true, formatter: 'number', formatoptions: { decimalSeparator: ".", thousandsSeparator: ',', decimalPlaces: 2 } }
],
sortname: 'Id',
sortorder: 'asc',
idPrefix: mainGridPrefix,
subGrid: true,
//localReader: { repeatitems: true },
jsonReader: { repeatitems: false},
autowidth: true,
shrinkToFit: true,
loadonce: true,
viewrecords: true,
rowNum: 5000,
pgbuttons: false,
pginput: false,
pager: "#jqGridPager",
caption: "Group Template",
altRows: true,
altclass: 'myAltRowClass',
beforeProcessing: function (data) {
var rows = data.rows, l = rows.length, i, item, subgrids = {};
for (i = 0; i < l; i++) {
item = rows[i];
if (item.groupItems) {
subgrids[item.id] = item.groupItems;
}
}
data.userdata = subgrids;
},
subGridRowExpanded: function (subgridDivId, rowId) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
pureRowId = $.jgrid.stripPref(mainGridPrefix, rowId),
subgrids = $(this).jqGrid("getGridParam", "userData"),
subgridPagerId = subgridDivId + "_p";
$("#" + $.jgrid.jqID(subgridDivId)).append($subgrid).append('<div id=' + subgridPagerId + '></div>');
$subgrid.jqGrid({
datatype: "local",
styleUI: 'Bootstrap',
data: subgrids[pureRowId],
editurl: 'clientArray',
colNames: ['Item', 'Item Description', 'Health Standard', 'Sort order', 'Statuses', 'Risks', 'Solutions', 'Budgets'],
colModel: [
{ name: 'itemName', width: '200', sortable: false, editable: true, editrules: { required: true }, editoptions: { maxlength: 50 } },
{ name: 'itemDescription', width: '400', sortable: false, editable: true, editoptions: { maxlength: 500 } },
{ name: 'healthStandard', width: '400', sortable: false, editable: true, editoptions: { maxlength: 500 } },
{ name: 'itemSortOrder', width: '200', sortable: false, editable: true, formatter: 'number', formatoptions: { decimalSeparator: ".", thousandsSeparator: ',', decimalPlaces: 2 } },
{ name: 'statuses', width: '400', sortable: false, editable: true, editoptions: { maxlength: 500 } },
{ name: 'risks', width: '400', sortable: false, editable: true, editoptions: { maxlength: 500 } },
{ name: 'solutions', width: '400', sortable: false, editable: true, editoptions: { maxlength: 500 } },
{ name: 'budgets', width: '400', sortable: false, editable: true, editoptions: { maxlength: 100 } }
],
//rownumbers: true,
rowNum: 5000,
autoencode: true,
autowidth: true,
pgbuttons: false,
viewrecords: true,
pginput: false,
jsonReader: { repeatitems: false, id: "groupId" },
gridview: true,
altRows: true,
altclass: 'myAltRowClass',
idPrefix: rowId + "_",
pager: "#" + subgridPagerId
});
$subgrid.jqGrid('navGrid', "#" + subgridPagerId, { edit: true, add: false, del: true, search: true, refresh: false, view: false }, // options
{ closeAfterEdit: true }, // edit options //recreateForm: true
{ closeAfterAdd: true }, // add options
{}, //del options
{} // search options
);
}
});
$('#jqGrid').navGrid('#jqGridPager', { edit: true, add: false, del: true, search: true, refresh: false, view: false }, // options
// options for Edit Dialog
{
editCaption: "Edit Group",
beforeShowForm: function (form) {
form.closest('.ui-jqdialog').center();
},
bottominfo: "<br/>",
recreateForm: true,
closeOnEscape: true,
closeAfterEdit: true
},
// options for Add Dialog
{
//url:'clientArray',
addCaption: "Add Group",
beforeShowForm: function (form) {
form.closest('.ui-jqdialog').center();
},
bottominfo: "<br/>",
recreateForm: true,
closeOnEscape: true,
closeAfterAdd: true
},
// options for Delete Dailog
{
caption: "Delete Group",
beforeShowForm: function (form) {
form.closest('.ui-jqdialog').center();
},
msg: "Are you sure you want to delete?",
recreateForm: true,
closeOnEscape: true,
closeAfterDelete: true
},
// options for Search Dailog
{
caption: "Search Group",
beforeShowForm: function (form) {
form.closest('.ui-jqdialog').center();
},
recreateForm: true,
closeOnEscape: true,
closeAfterDelete: true
}
);
There was a small bug in the form editing which is fixed now. Thank you for help us to find them.
Now to the problem.
When you add data in main grid it is natural to add a unique id of every row. Since of the bug instead of inserting a row with the Guriddo id Generator there was a wrong insertion with id = s_empty. This causes every inserted row in main grid to have same id, which is not correct.
The fix is published in GitHub and you can try it.
We have updated your demo in order to insert correct the data in the subgrid. The only small addition is in afterSubmit event in add mode, where the needed item is created.
Hope this will solve the problem
Here is the demo with the fixed version
Edited
At server you can analyze the id column if contain string 'jqg', which will point you that this is a new row. The corresponding id for the subgrid is in userData module which will connect the main grid id with the subgrid data
EDIT 2
One possible solution to what you want to achieve is to get the main data and the to get the subgrid data using userData property. After this make a loop to main data and update it like this
var maindata = $("#jqGrid").jqGrid('getGridParam', 'data');
var subgrids = $("#jqGrid").jqGrid('getGridParam', 'userData');
for(var i= 0;i < maindata.length;i++) {
var key = maindata[i].id;
if(subgrids.hasOwnProperty(key) ) {
if(!maindata[i].hasOwnProperty(groupItems) ) {
maindata[i].groupItems = [];
}
maindata[i].groupItems = subgrids[key];
}
}
The code is not tested, but I think you got the idea.
The other way is to update the groupitems on every CRUD of subgrid, which I think is not so difficult to achieve.

JqGrid pgtext issue

pgtext is not displaying properly in the pager. What could be the reason?
Grid Options
pager: pagerID,
gridview: true,
navOptions: {
position: "left",
addtext: "Add",
edittext: "Edit",
deltext: "Delete",
iconsOverText: true
},
loadonce: false,
pagerpos: 'center',
rowNum: pagesize,
viewrecords: true,
Pager Setting
$("#"+childGridID).navGrid(pagerID,
// the buttons to appear on the toolbar of the grid
{ edit: true, add: true, del: true, search: false,
refresh: false, view: false, cloneToTop: false },
// options for the Edit Dialog
{...........................

how to add refresh button to jqgrid toolbar?

i am working on jqgrid. i want to add refresh button to jqgrid toolbar to refresh the grid.
here is my js code:
jQuery(document).ready(function () {
var grid = jQuery("#gridemp");
grid.jqGrid({
url: '/Admin/GetTimeInOut_ForAdmin',
datatype: 'json',
mtype: 'Post',
height: '100%',
multipleSearch: false,
rownumbers: true,
//formatCell: emptyText,
colNames: ['User', 'Date', 'TimeIn', 'TimeOut'],
colModel: [
{ name: 'User', index: 'User', align: "center", sorttype: 'text', resizable: true, editable: false },
{ name: 'Date', index: 'Date', align: "center", sorttype: 'text', resizable: true, editable: false, searchoptions: { dataInit: function (el) { $(el).datepicker({ dateFormat: 'mm/dd/yy' }).change(function () { $('#gridemp')[0].triggerToolbar(); }); } } },
{ name: 'TimeIn', index: 'TimeIn', align: "center", sorttype: 'text', resizable: true, editable: false },
{ name: 'TimeOut', index: 'TimeOut', align: "center", sort:false, resizable: true, editable: false }
],
//shrinkToFit: true,
// loadonce: false,
//ignoreCase: true,
width: '690',
pager: '#emppager',
caption: 'Employee Time IN/OUT',
rowNum: 10,
rowList: [10, 20, 50, 100],
viewrecords: true,
hidegrid: false,
}
);
grid.jqGrid('filterToolbar',{ stringResult: true, searchOnEnter: true, defaultSearch: 'cn' });
grid.jqGrid('navGrid', '#emppager',
{ resize: false, add: false, search: false, del: false, refresh: false, edit: false, alerttext: 'Please select one user' }
).jqGrid('navButtonAdd', '#pager');
});
actually i need 2 refresh buttons one for to clear the search bar text boxes without refreshing the jqgrid, and one for refreshing the whole grid. i will mark your answer if it works for me. thanks in advance. happy coding :), if you the question is not clear please comment i will explain.
First of all it seems your code contains typing error: you use pager: '#emppager' during creating grid, in navGrid but not in navButtonAdd.
To add "standard" reload button which reset filter toolbar and reload the grid you need just remove refresh: false option.
To add custom clear filter you need call navButtonAdd in the way like below
.jqGrid("navButtonAdd", "#emppager", {
caption: "", // no text near the button
title: "Clear filters in toolbar without reloading of data",
buttonicon: "ui-icon-close", // an example of icon
onClickButton: function () {
this.clearToolbar(false); // don't reload grid
}
});
You can change icon used by Refresh button by usage refreshicon option (at the same place where you specify del, refresh, alerttext etc). Default value is refreshicon: "ui-icon-refresh". Moreover you can consider to use refreshstate: "current" (default is refreshstate: "firstpage").

jqgrid, alert with arror after failet add record to database

it's my code:
<script type="text/javascript">
var grid = $("#list");
$(function(){
var grid = $("#list");
grid.jqGrid({
url:'grid.php',
datatype: 'xml',
mtype: 'GET',
colNames:['ID sprzętu','Kod sprzętu', 'Właściciel','Konfiguracja'],
colModel :[
{name:'SprzetID', index:'SprzetID', width:90},
{name:'Kod', index:'Kod', width:120, editable: true},
{name:'Wlasciciel', index:'Wlasciciel', width:200, align:'left', editable: true},
{name:'Konfiguracja', index:'Konfiguracja', width:400, align:'left', editable: true},
],
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'SprzetID',
sortorder: 'asc',
viewrecords: true,
gridview: true,
caption: 'Lista sprzętu'
});
grid.jqGrid('navGrid','#pager',
{add: true, edit: true, del: true, search: true}, //options
{width:400, }, // edit options
{width:400,closeAfterAdd: true, url:'add.php'}, // add options
{reloadAfterSubmit:false}, // del options
{width:600} // search options
);
});
All is great, when adding record to database is correctly, but when for example field "Kod" is duplicate (it's unique field), record can't be add to database... and isn't. I want to display alert with error message, but I can't find in documentation how to do it... I gues,I should use "afterSubmit", but how... I don't know.
Resolved. In add parameters I added code:
afterSubmit: function(response, postdata) {
if(response.responseText != ""){
return [false, response.responseText];
}else{
return [true,"Ok"];
}}

Resources