使用 jqgrid 以与完成搜索相同的方式进行过滤
Use jqgrid to filter in the same way searching is done
让我看看我能否解释一下...
我有一个产品网格,搜索工作正常,我设置了一个自定义按钮来过滤 json 中不在网格中的特定项目,现在我正在制作一个 ajax 调用(使用 VisualForce)获取 json 然后我将其存储在全局变量中,然后再使用 json 加载网格,然后加载网格。选择过滤器后,我构建了一个包含过滤器的 json 的临时数组,然后将产品网格设置为新数组。然后我进行重置,因此如果更改或删除过滤器,它将首先获取我之前设置的全局变量并重新应用新过滤器,但是当我 clearGridData
它也会清空我的全局变量,所以当我单击重置它只会重新加载零行的网格。
我猜我正在做的是错误的方法所以我想知道搜索是如何工作的,你搜索一个项目它只显示网格中的匹配项然后简单地按下重新加载它重新加载所有记录回网格。我需要我的过滤器以相同的方式工作。
var cart = [];
var cartMade = false;
var cartSubmitted = false;
var sfOpportunityId;
var filteredProducts = [];
var fullProductList = [];
function GetFilteredProducts(){
//reload products with filtered array
var products = $("#productsTable").jqGrid('getGridParam','data');
var selected = $("#filterByFieldDropDown option:selected").val();
switch(selected){
case "common" :
filteredProducts = $.grep(products, function(value) {
return value.IsCommonItem == true;
});
break;
case "sos-common" :
filteredProducts = $.grep(products, function(value) {
return value.IsCommonSosItem == true;
});
break;
case "uncommon" :
filteredProducts = $.grep(products, function(value) {
return value.IsCommonItem == false;
});
break;
}
RemoveProductFilter();
$("#productsTable").jqGrid('clearGridData')
.jqGrid('setGridParam', { data: filteredProducts})
.trigger("reloadGrid");
}
function RemoveProductFilter() {
$("#productsTable").jqGrid('clearGridData')
.jqGrid('setGridParam', { data: fullProductList})
.trigger("reloadGrid");
$("#filter-dialog-form").dialog("close");
}
function QueryServerForProducts() {
$(".spinner").show();
var ajaxCall = '{!$RemoteAction.AddProductsCustom.GetProducts}';
sfOpportunityId = requestQueryString("id")
GetCart();
// Get Products and put them into product grid
Visualforce.remoting.Manager.invokeAction(
ajaxCall,
sfOpportunityId,
function(result, event){
if (event.status) {
$(".spinner").hide();
var parsedResult = JSON.parse(DecodeAscii(result));
fullProductList = parsedResult;
CreateProductGrid(parsedResult);
} else if (event.type === 'exception') {
ShowErrorLabel("ERROR in ajax call(" + ajaxCall + "): \n" + event.message);
} else {
ShowWarningLabel("Problem w/ ajax call(" + ajaxCall + "): \n" + event.message);
}
},
{escape: true}
);
}
function CreateProductGrid(result){
var previouslySelectedRow = null;
var rowIsSelected = null;
var previousRowIsSelected = null;
var currentRowId;
var currentCount;
var cancelEditing = function(theGrid) {
var lrid;
if (typeof previouslySelectedRow !== "undefined") {
// cancel editing of the previous selected row if it was in editing state.
// jqGrid hold intern savedRow array inside of jqGrid object,
// so it is safe to call restoreRow method with any id parameter
// if jqGrid not in editing state
theGrid.jqGrid('restoreRow', previouslySelectedRow);
// now we need to restore the icons in the formatter:"actions"
lrid = $.jgrid.jqID(previouslySelectedRow);
$("tr#" + lrid + " div.ui-inline-edit").show();
$("tr#" + lrid + " div.ui-inline-save, " + "tr#" + lrid + " div.ui-inline-cancel").hide();
}
};
$("#productsTable").jqGrid({
data: result,
datatype: "local",
colNames: [
'Add', 'Product Name', 'Product Code', 'Customer Price'
],
colModel: [
{ name: "actions", template: "actions", width: 50, formatoptions:{
delbutton: false,
editbutton: false
}},
{ name: 'ProductName', index: 'ProductName', width: 650, search: true, searchoptions:{sopt:['eq','bw','bn','cn','nc','ew','en']} },
{ name: 'ProductCode', index: 'ProductCode', width: 150, search: true, searchoptions:{sopt:['eq','bw','bn','cn','nc','ew','en']} },
{ name: 'UnitPrice', index: 'UnitPrice', width: 100, search: false, formatter: 'currency', formatoptions:{decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 2, prefix: "$"}}
],
rowNum: 25,
rowList: [15, 25, 50, 100],
pager: true,
viewrecords: true,
sortname: 'ProductName',
iconSet: "fontAwesome",
sortorder: 'asc',
localReader: {id: "ProductId" },
caption: "Products",
navOptions: {
edit: false,
add: false,
del: false,
searchtext: "<span class='ui-pg-button-text'>Search</span>",
refreshtext: "<span class='ui-pg-button-text'>Reload</span>",
iconsOverText: true
},
inlineNavOptions: {
edit: false,
add: false,
del: false
},
searching: {
overlay: false,
multipleSearch: true,
closeAfterSearch: true,
closeOnEscape: true,
showQuery: true
},
actionsNavOptions: {
addToCarticon: "fa-shopping-cart",
addToCarttitle: "Add product to the cart",
custom: [
{ action: "addToCart", position: "first", onClick: function (options) {
var rowData = $('#productsTable').getLocalRow(options.rowid);
var cartButton = $("#jAddToCartButton_"+options.rowid).find("span");
if(cartButton.hasClass("fa-ban")){
DeleteProductFromOpportunity(JSON.stringify(rowData));
cart = $.grep(cart, function(value) {
return value.ProductId !== rowData.ProductId;
});
//reload cart with new array
reloadCart();
cartButton.removeClass("fa-ban");
cartButton.addClass("fa-shopping-cart");
}
else if(cartButton.hasClass("fa-shopping-cart")){
cart.push(rowData);
//reload cart with new array
reloadCart();
cartButton.removeClass("fa-shopping-cart");
cartButton.addClass("fa-ban");
}
}
}]
},
loadComplete: function() {
//for each object in cart
//if product ID matches product Id in product
//grid then set button to a cancel icon
if(cart.length !== 0){
var cartIds = [];
var jsonCart = JSON.stringify(cart);
var parsedJsonCart = JSON.parse(jsonCart);
var productsInCart = $.grep(parsedJsonCart, function(el, i){
cartIds.push(el.ProductId);
});
var currentRows = $('#productsTable').jqGrid('getGridParam', 'data')
var shownProductsThatAreInCart = $.grep(currentRows, function (el, i) {
return $.inArray(el.ProductId, cartIds) !== -1;
});
if(shownProductsThatAreInCart.length > 0){
var rowIds = $(this).jqGrid('getDataIDs');
$.each(rowIds, function(k, v) {
rowData = $('#productsTable').getLocalRow(v);
if($.inArray(rowData['ProductId'], cartIds) !== -1){
//alert("Matched Product:\nRowData['ProductId'] = " + rowData['ProductId'] + "\nto\nProduct in cart: " + cartIds.Id);
var cartButton = $("#jAddToCartButton_"+v).find("span");
cartButton.removeClass("fa-shopping-cart");
cartButton.addClass("fa-ban");
}
});
}
}
}
})
.jqGrid('navGrid')
.jqGrid("navButtonAdd", {
iconsOverText: true,
caption:"<span class='ui-pg-button-text'>Filter</span>",
buttonicon: "fa-filter",
onClickButton: function() {
InitializeFilterDialog();
$("#filter-dialog-form").dialog("open");
},
title:"Filter",
position: "first"
})
.jqGrid("navButtonAdd", {
iconsOverText: true,
caption:"<span class='ui-pg-button-text'>View Cart</span>",
buttonicon: "fa-shopping-cart",
onClickButton: function() {
InitializeProductCartDialog();
ShowCart();
},
title:"View Cart"
});
}
我建议您加载所有数据并仅在网格上应用过滤器。固定代码可能如下:
var mydata = [
{"id":"1","invdate":"2010-05-24","name":"test","note":"note","tax":"10.00","total":"2111.00","isCommon":"true","isCommonSos":"true"},
...
{"id":"29","invdate":"2007-09-01","name":"test3","note":"note3","amount":"400.00","tax":"30.00","total":"430.00","isCommon":"true","isCommonSos":"false"}
],
$grid = $("#productsTable");
$grid.jqGrid({
data: mydata,
rowNum: 10,
rowList: [10,20,30],
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id', width:60, sorttype:"int"},
{name:'invdate', width:90, sorttype:"date", formatter:"date"},
{name:'name', width:100},
{name:'amount', width:80, align:"right",sorttype:"float", formatter:"number"},
{name:'tax', width:80, align:"right",sorttype:"float"},
{name:'total', width:80,align:"right",sorttype:"float"},
{name:'note', width:100, sortable:false}
],
pager: true,
viewrecords: true,
caption: "Filtering Array Data",
additionalProperties: ["isCommon", "isCommonSos"],
iconSet: "fontAwesome"
});
$("#applyFilter").on("click", function() {
GetFilteredProducts();
});
$("#clearFilter").on("click", function() {
var p = $grid.jqGrid("getGridParam");
delete p.postData.filters;
p.search = false;
$grid.trigger("reloadGrid");
});
function GetFilteredProducts(){
//reload products with filtered array
var selected = $("#filterByFieldDropDown").val(),
p = $grid.jqGrid("getGridParam");
switch(selected){
case "common" :
p.postData.filters = JSON.stringify({
groupOp: "AND",
groups: [],
rules: [{field: "isCommon", op: "eq", data: "true"}]
});
break;
case "sos-common" :
p.postData.filters = JSON.stringify({
groupOp: "AND",
groups: [],
rules: [{field: "isCommonSos", op: "eq", data: "true"}]
});
break;
case "uncommon" :
p.postData.filters = JSON.stringify({
groupOp: "AND",
groups: [],
rules: [{field: "isCommon", op: "eq", data: "false"}]
});
break;
}
p.search = true;
$grid.trigger("reloadGrid");
}
查看固定演示 https://jsfiddle.net/OlegKi/36wkfzs4/2/。
免费的 jqGrid 支持按输入数据的任何附加属性 以与按列相同的方式进行过滤和排序。如果你需要 filter/sort 字符串属性,你可以在 additionalProperties
中添加属性列表,就像我在上面的演示中使用 additionalProperties: ["isCommon", "isCommonSos"]
一样。您也可以将属性用作 sortname
的值,以强制按 属性.
排序
如果您想将 属性 的内容解释为数字或整数,那么您可以使用另一种形式的 additionalProperties
:and 对象具有两个属性 name
和 sorttype
。例如,您可以删除列 id
并使用 additionalProperties: ["isCommon", {name: "id", sorttype: "integer"}, "isCommonSos"]
。要将数据解释为日期,您应该添加 formatter: "date"
。您可以另外指定 formatoptions
和 srcformat
和 newformat
。一般来说,additionalProperties
的数字和日期格式可以是 colModel
中使用的设置的子集。您可以只移动一些列,您希望它们始终隐藏到 additionalProperties
,并且所有列都将以与隐藏列相同的方式工作,但网格的 DOM 会更小。
让我看看我能否解释一下...
我有一个产品网格,搜索工作正常,我设置了一个自定义按钮来过滤 json 中不在网格中的特定项目,现在我正在制作一个 ajax 调用(使用 VisualForce)获取 json 然后我将其存储在全局变量中,然后再使用 json 加载网格,然后加载网格。选择过滤器后,我构建了一个包含过滤器的 json 的临时数组,然后将产品网格设置为新数组。然后我进行重置,因此如果更改或删除过滤器,它将首先获取我之前设置的全局变量并重新应用新过滤器,但是当我 clearGridData
它也会清空我的全局变量,所以当我单击重置它只会重新加载零行的网格。
我猜我正在做的是错误的方法所以我想知道搜索是如何工作的,你搜索一个项目它只显示网格中的匹配项然后简单地按下重新加载它重新加载所有记录回网格。我需要我的过滤器以相同的方式工作。
var cart = [];
var cartMade = false;
var cartSubmitted = false;
var sfOpportunityId;
var filteredProducts = [];
var fullProductList = [];
function GetFilteredProducts(){
//reload products with filtered array
var products = $("#productsTable").jqGrid('getGridParam','data');
var selected = $("#filterByFieldDropDown option:selected").val();
switch(selected){
case "common" :
filteredProducts = $.grep(products, function(value) {
return value.IsCommonItem == true;
});
break;
case "sos-common" :
filteredProducts = $.grep(products, function(value) {
return value.IsCommonSosItem == true;
});
break;
case "uncommon" :
filteredProducts = $.grep(products, function(value) {
return value.IsCommonItem == false;
});
break;
}
RemoveProductFilter();
$("#productsTable").jqGrid('clearGridData')
.jqGrid('setGridParam', { data: filteredProducts})
.trigger("reloadGrid");
}
function RemoveProductFilter() {
$("#productsTable").jqGrid('clearGridData')
.jqGrid('setGridParam', { data: fullProductList})
.trigger("reloadGrid");
$("#filter-dialog-form").dialog("close");
}
function QueryServerForProducts() {
$(".spinner").show();
var ajaxCall = '{!$RemoteAction.AddProductsCustom.GetProducts}';
sfOpportunityId = requestQueryString("id")
GetCart();
// Get Products and put them into product grid
Visualforce.remoting.Manager.invokeAction(
ajaxCall,
sfOpportunityId,
function(result, event){
if (event.status) {
$(".spinner").hide();
var parsedResult = JSON.parse(DecodeAscii(result));
fullProductList = parsedResult;
CreateProductGrid(parsedResult);
} else if (event.type === 'exception') {
ShowErrorLabel("ERROR in ajax call(" + ajaxCall + "): \n" + event.message);
} else {
ShowWarningLabel("Problem w/ ajax call(" + ajaxCall + "): \n" + event.message);
}
},
{escape: true}
);
}
function CreateProductGrid(result){
var previouslySelectedRow = null;
var rowIsSelected = null;
var previousRowIsSelected = null;
var currentRowId;
var currentCount;
var cancelEditing = function(theGrid) {
var lrid;
if (typeof previouslySelectedRow !== "undefined") {
// cancel editing of the previous selected row if it was in editing state.
// jqGrid hold intern savedRow array inside of jqGrid object,
// so it is safe to call restoreRow method with any id parameter
// if jqGrid not in editing state
theGrid.jqGrid('restoreRow', previouslySelectedRow);
// now we need to restore the icons in the formatter:"actions"
lrid = $.jgrid.jqID(previouslySelectedRow);
$("tr#" + lrid + " div.ui-inline-edit").show();
$("tr#" + lrid + " div.ui-inline-save, " + "tr#" + lrid + " div.ui-inline-cancel").hide();
}
};
$("#productsTable").jqGrid({
data: result,
datatype: "local",
colNames: [
'Add', 'Product Name', 'Product Code', 'Customer Price'
],
colModel: [
{ name: "actions", template: "actions", width: 50, formatoptions:{
delbutton: false,
editbutton: false
}},
{ name: 'ProductName', index: 'ProductName', width: 650, search: true, searchoptions:{sopt:['eq','bw','bn','cn','nc','ew','en']} },
{ name: 'ProductCode', index: 'ProductCode', width: 150, search: true, searchoptions:{sopt:['eq','bw','bn','cn','nc','ew','en']} },
{ name: 'UnitPrice', index: 'UnitPrice', width: 100, search: false, formatter: 'currency', formatoptions:{decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 2, prefix: "$"}}
],
rowNum: 25,
rowList: [15, 25, 50, 100],
pager: true,
viewrecords: true,
sortname: 'ProductName',
iconSet: "fontAwesome",
sortorder: 'asc',
localReader: {id: "ProductId" },
caption: "Products",
navOptions: {
edit: false,
add: false,
del: false,
searchtext: "<span class='ui-pg-button-text'>Search</span>",
refreshtext: "<span class='ui-pg-button-text'>Reload</span>",
iconsOverText: true
},
inlineNavOptions: {
edit: false,
add: false,
del: false
},
searching: {
overlay: false,
multipleSearch: true,
closeAfterSearch: true,
closeOnEscape: true,
showQuery: true
},
actionsNavOptions: {
addToCarticon: "fa-shopping-cart",
addToCarttitle: "Add product to the cart",
custom: [
{ action: "addToCart", position: "first", onClick: function (options) {
var rowData = $('#productsTable').getLocalRow(options.rowid);
var cartButton = $("#jAddToCartButton_"+options.rowid).find("span");
if(cartButton.hasClass("fa-ban")){
DeleteProductFromOpportunity(JSON.stringify(rowData));
cart = $.grep(cart, function(value) {
return value.ProductId !== rowData.ProductId;
});
//reload cart with new array
reloadCart();
cartButton.removeClass("fa-ban");
cartButton.addClass("fa-shopping-cart");
}
else if(cartButton.hasClass("fa-shopping-cart")){
cart.push(rowData);
//reload cart with new array
reloadCart();
cartButton.removeClass("fa-shopping-cart");
cartButton.addClass("fa-ban");
}
}
}]
},
loadComplete: function() {
//for each object in cart
//if product ID matches product Id in product
//grid then set button to a cancel icon
if(cart.length !== 0){
var cartIds = [];
var jsonCart = JSON.stringify(cart);
var parsedJsonCart = JSON.parse(jsonCart);
var productsInCart = $.grep(parsedJsonCart, function(el, i){
cartIds.push(el.ProductId);
});
var currentRows = $('#productsTable').jqGrid('getGridParam', 'data')
var shownProductsThatAreInCart = $.grep(currentRows, function (el, i) {
return $.inArray(el.ProductId, cartIds) !== -1;
});
if(shownProductsThatAreInCart.length > 0){
var rowIds = $(this).jqGrid('getDataIDs');
$.each(rowIds, function(k, v) {
rowData = $('#productsTable').getLocalRow(v);
if($.inArray(rowData['ProductId'], cartIds) !== -1){
//alert("Matched Product:\nRowData['ProductId'] = " + rowData['ProductId'] + "\nto\nProduct in cart: " + cartIds.Id);
var cartButton = $("#jAddToCartButton_"+v).find("span");
cartButton.removeClass("fa-shopping-cart");
cartButton.addClass("fa-ban");
}
});
}
}
}
})
.jqGrid('navGrid')
.jqGrid("navButtonAdd", {
iconsOverText: true,
caption:"<span class='ui-pg-button-text'>Filter</span>",
buttonicon: "fa-filter",
onClickButton: function() {
InitializeFilterDialog();
$("#filter-dialog-form").dialog("open");
},
title:"Filter",
position: "first"
})
.jqGrid("navButtonAdd", {
iconsOverText: true,
caption:"<span class='ui-pg-button-text'>View Cart</span>",
buttonicon: "fa-shopping-cart",
onClickButton: function() {
InitializeProductCartDialog();
ShowCart();
},
title:"View Cart"
});
}
我建议您加载所有数据并仅在网格上应用过滤器。固定代码可能如下:
var mydata = [
{"id":"1","invdate":"2010-05-24","name":"test","note":"note","tax":"10.00","total":"2111.00","isCommon":"true","isCommonSos":"true"},
...
{"id":"29","invdate":"2007-09-01","name":"test3","note":"note3","amount":"400.00","tax":"30.00","total":"430.00","isCommon":"true","isCommonSos":"false"}
],
$grid = $("#productsTable");
$grid.jqGrid({
data: mydata,
rowNum: 10,
rowList: [10,20,30],
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id', width:60, sorttype:"int"},
{name:'invdate', width:90, sorttype:"date", formatter:"date"},
{name:'name', width:100},
{name:'amount', width:80, align:"right",sorttype:"float", formatter:"number"},
{name:'tax', width:80, align:"right",sorttype:"float"},
{name:'total', width:80,align:"right",sorttype:"float"},
{name:'note', width:100, sortable:false}
],
pager: true,
viewrecords: true,
caption: "Filtering Array Data",
additionalProperties: ["isCommon", "isCommonSos"],
iconSet: "fontAwesome"
});
$("#applyFilter").on("click", function() {
GetFilteredProducts();
});
$("#clearFilter").on("click", function() {
var p = $grid.jqGrid("getGridParam");
delete p.postData.filters;
p.search = false;
$grid.trigger("reloadGrid");
});
function GetFilteredProducts(){
//reload products with filtered array
var selected = $("#filterByFieldDropDown").val(),
p = $grid.jqGrid("getGridParam");
switch(selected){
case "common" :
p.postData.filters = JSON.stringify({
groupOp: "AND",
groups: [],
rules: [{field: "isCommon", op: "eq", data: "true"}]
});
break;
case "sos-common" :
p.postData.filters = JSON.stringify({
groupOp: "AND",
groups: [],
rules: [{field: "isCommonSos", op: "eq", data: "true"}]
});
break;
case "uncommon" :
p.postData.filters = JSON.stringify({
groupOp: "AND",
groups: [],
rules: [{field: "isCommon", op: "eq", data: "false"}]
});
break;
}
p.search = true;
$grid.trigger("reloadGrid");
}
查看固定演示 https://jsfiddle.net/OlegKi/36wkfzs4/2/。
免费的 jqGrid 支持按输入数据的任何附加属性 以与按列相同的方式进行过滤和排序。如果你需要 filter/sort 字符串属性,你可以在 additionalProperties
中添加属性列表,就像我在上面的演示中使用 additionalProperties: ["isCommon", "isCommonSos"]
一样。您也可以将属性用作 sortname
的值,以强制按 属性.
如果您想将 属性 的内容解释为数字或整数,那么您可以使用另一种形式的 additionalProperties
:and 对象具有两个属性 name
和 sorttype
。例如,您可以删除列 id
并使用 additionalProperties: ["isCommon", {name: "id", sorttype: "integer"}, "isCommonSos"]
。要将数据解释为日期,您应该添加 formatter: "date"
。您可以另外指定 formatoptions
和 srcformat
和 newformat
。一般来说,additionalProperties
的数字和日期格式可以是 colModel
中使用的设置的子集。您可以只移动一些列,您希望它们始终隐藏到 additionalProperties
,并且所有列都将以与隐藏列相同的方式工作,但网格的 DOM 会更小。