I\'m using jqGrid with the filter toolbar, i need to set an initial default filter value to one of the fields so that only rows with status \'Open\' are displayed by default
I fixed it in different way then the answers above, im abusing the beforeRequest function to add initial de default values to the post data.
Had contact with the creator of jqGrid, the default value option is only for advanced searching.
I Wrote an function that you can set on the onBeforeRequest function that function will grab all default values in search options and append it to the post data. So the default value will be added in the initial request.
To ensure you still can use the onbeforeRequest event I`m change the onBeforeRequest in the end of the code (this.p.beforeRequest = function() {}). You can change it into what ever you want and call it. The next time you'll do an request that function will be used and this function will be dismissed (because of overriding).
function() {
var defaultSearchOptions = [];
var colModel = this.p.colModel;
// loop trough each column and check if they have an default value in search options
// and add them to the array
$.each(colModel, function (index, column) {
if (column.hasOwnProperty('searchoptions')) {
var searchOptions = column.searchoptions;
if (searchOptions.hasOwnProperty('defaultValue')) {
defaultSearchOptions[defaultSearchOptions.length++] =
{
""field"": column.index,
""op"": ""bw"",
""data"": searchOptions.defaultValue
};
}
}
});
// if there are any default search options retrieve the post data
if (defaultSearchOptions.length > 0) {
var postData = this.p.postData;
var filters = {};
// check if post data already has filters
if (postData.hasOwnProperty('filters')) {
filters = JSON.parse(postData.filters);
}
var rules = [];
// check if filtes already has rules
if (filters.hasOwnProperty('rules')) {
rules = filters.rules;
}
// loop trough each default search option and add the search option if the filter rule doesnt exists
$.each(defaultSearchOptions, function (defaultSearchOptionindex, defaultSearchOption) {
var ruleExists = false;
$.each(rules, function (index, rule) {
if (defaultSearchOption.field == rule.field) {
ruleExists = true;
return;
}
});
if (ruleExists == false) {
rules.push(defaultSearchOption);
}
});
filters.groupOp = 'AND';
filters.rules = rules;
// set search = true
postData._search = true;
postData.filters = JSON.stringify(filters);
}
this.p.beforeRequest = function() { // your before request function here };
this.p.beforeRequest.call(this);
}
Hope this helps