SAPUI5 (27) - 基于 ODataModel 的筛选

OData Service Filtering

OData 服务提供了筛选的功能,基于服务器端的筛选。方法是在 URL 的后面加上筛选参数 $filter= 。http://www.odata.org/documentation/odata-version-2-0/uri-conventions/ 页面有比较详细的介绍,这里仅对要点进行说明。

筛选在 OData 服务中,被称作 Filter System Query Option。我们先来看一个简单的例子,比如要查询城市为 Redmond 的供应商,我们可以使用 GET 方法,URL 为:

http://services.odata.org/V3/(S(user-token))/OData/OData.svc/Suppliers
    ?$filter=Address/City eq 'Redmond'

当然,浏览器中的URL是不能含有空格和特殊字符的,所以该URL中的空格被替换成 %20, 而单引号被替换成 %27

http://services.odata.org/V3/(S(user-token))/OData/OData.svc/Suppliers
    ?$filter=Address/City%20eq%20%27Redmond%27

逻辑操作符

  • eq: 等于 (Equal)
  • ne: 不等于 (Not equal)
  • gt: 大于 (Greater than)
  • ge: 大le于或等于 (Greater than or equal)
  • lt: 小于 (Less than)
  • le: 小于或等于 (Less than or equal)
  • 逻辑上的 and / or / not

字符串操作符

主要掌握:substringof, startswith 和 endswith

sap.ui.model.fiterOperator定义了相应的操作符,但是对于 and/or 采取了不同的方法。

  • sap.ui.model.FilterOperator.EQ: 对应 eq
  • sap.ui.model.FilterOperator.NE: 对应 ne
  • sap.ui.model.FilterOperator.GT: 对应 gt
  • sap.ui.model.FilterOperator.GE: 对应 ge
  • sap.ui.model.FilterOperator.LT: 对应 lt
  • sap.ui.model.FilterOperator.LE: 对应 le
  • sap.ui.model.FilterOperator.Contains: 对应 substringof
  • sap.ui.model.FilterOperator.StartsWidth: 对应 startswith
  • sap.ui.model.FilterOperator.EndsWith: 对应 endswith

基于oDataModel实现筛选

read() 方法的 filters 属性

oDataModelread() 方法中 filters 属性可以对请求数据进行筛选。先给出代码:

// application model
var sServiceUrl = "https://cors-anywhere.herokuapp.com/" 
                + "http://services.odata.org/V3/Northwind/Northwind.svc/";
var oModel = new sap.ui.model.odata.v2.ODataModel(sServiceUrl);
oModel.setUseBatch(false);
sap.ui.getCore().setModel(oModel);

// define filters
var aFilters = [
    new sap.ui.model.Filter("ProductName", 
            sap.ui.model.FilterOperator.Contains,
            "Chocolate")
];

// get data using filter
oModel.read("/Products", {
    filters: aFilters,     
    success: function(oData, oResponse){
        console.log(oData);
    }
});			
  • 代码说明:
    • new sap.ui.model.Filter('path', operator, queryValue) 实例化 sap.ui.model.Filter 对象,每一个对象代表一个筛选的条件。比如上面的代码中,筛选条件为 ProductName 包含 Chocolate。

    • oDataModelread() 方法包含 filters 属性,这个属性是为sap.ui.model.Filter 实例的数组,代表一个筛选条件或多个筛选条件的组合。

在 Chrome 浏览器中执行,然后通过 F12 查看 Console 页面的输出,可以看到如下内容:

SAPUI5 (27) - 基于 ODataModel 的筛选_第1张图片

Northwind data service 产品中只有一个名称含有 Chocolate 的 产品,所以返回的数组中只有一个值。

切换到 Network 页面,可以看到,当执行 read() 方法时,向服务器提交的请求包含 $filter

SAPUI5 (27) - 基于 ODataModel 的筛选_第2张图片

在右边的 Headers 页签,如果我们浏览到最下面,可以清楚地看到 Query String Parameters:

SAPUI5 (27) - 基于 ODataModel 的筛选_第3张图片

说一说请求的 Batch 模式。Batch 模式指在发送 Http Request 的时候,框架自动合并请求和响应 (Response), 从而减少网络通讯的次数,提高性能。在实际应用的代码中,一般都应该使用Batch 模式。但在开发和代码跟踪的时候,通过oModel.setUseBatch(false); 设置不使用 Batch 模式,有利于查看和分析 Http 请求和响应。

多条件筛选

oDataModel.read() 方法中 filters 属性是 sap.ui.model.Filter数组,如果多个筛选组合在一起,这些筛选之间默认是 and 关系,如果需要用 or 关系,需要实例化一个新的 Fiter 对象,并且将第二个参数设为 false。下面的代码在 Products 中筛选出以 C 开头 或以 O 开头 的 产品名称:

// application model
var sServiceUrl = "https://cors-anywhere.herokuapp.com/" 
                + "http://services.odata.org/V3/Northwind/Northwind.svc/";
var oModel = new sap.ui.model.odata.v2.ODataModel(sServiceUrl);
oModel.setUseBatch(false);
sap.ui.getCore().setModel(oModel);

// 多条件筛选
var oProductFilter1 = new sap.ui.model.Filter(
    "ProductName",
    sap.ui.model.FilterOperator.StartsWith,
    "C"
);

var oProductFilter2 = new sap.ui.model.Filter(
    "ProductName",
    sap.ui.model.FilterOperator.StartsWith,
    "O"
);

// 实例化一个新的Filter, 参数2为false
var oFilterGroup = new sap.ui.model.Filter([oProductFilter1, oProductFilter2], false);
var aFilters = [oFilterGroup];

// get data using filter
oModel.read("/Products", {
    filters: aFilters,     
    success: function(oData, oResponse){
        console.log(oData);
    }
});		

数据绑定中实现筛选

通过控件的数据绑定,筛选需要用到 sap.ui.model.ListBindg 类的 filter() 方法。运行后的界面如下:

SAPUI5 (27) - 基于 ODataModel 的筛选_第4张图片

在 SearchField 中输入条件,点击放大镜,将按条件进行筛选。先给出完整代码:

<!DOCTYPE HTML>
<html>
	<head>
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>

		<script src="../../resources/sap-ui-core.js"
				id="sap-ui-bootstrap"
				data-sap-ui-libs="sap.m"
				data-sap-ui-theme="sap_bluecrystal">
		</script>
		<!-- only load the mobile lib "sap.m" and the "sap_bluecrystal" theme -->

		<script>
		
			// application model
			var sServiceUrl = "https://cors-anywhere.herokuapp.com/" 
			                + "http://services.odata.org/V3/Northwind/Northwind.svc/";
			var oModel = new sap.ui.model.odata.v2.ODataModel(sServiceUrl);
			oModel.setUseBatch(false);
			sap.ui.getCore().setModel(oModel);
			
			// 按选择条件执行筛选
			onFilterProducts = function(oEvent){
				var sQueryVal = oEvent.getParameter("query");				
				var aFilters = [];
				
				if (sQueryVal){
					var oProductFilter = new sap.ui.model.Filter(
							"ProductName",
							sap.ui.model.FilterOperator.Contains,
							sQueryVal);
					aFilters.push(oProductFilter);
				}
				
				var oList = sap.ui.getCore().byId("ProductList");
				var oBinding = oList.getBinding("items");

				oBinding.filter(aFilters);
			}
			
			
			sap.ui.getCore().attachInit(function(){
				var oList = new sap.m.List({
					id: "ProductList",
					width: "auto"
				});
				
				oList.setHeaderToolbar(new sap.m.Toolbar({
					title: "库存产品清单",
					content: [
					   new sap.m.ToolbarSpacer(),
					   new sap.m.SearchField({width: "50%", search: onFilterProducts})
					]
				}));
				
				oList.bindItems({
					path: "/Products",
					template: new sap.m.ObjectListItem({
						title: "{ProductName}",
						number: "{UnitPrice}",
						numberUnit: "EUR"
					})
				});
				
				var oPage = new sap.m.Page({
					title: "oDataModel 筛选测试",
					content: [oList]
				});
				
				var oApp = new sap.m.App({
					initialPage: oPage
				});
				
				oApp.addPage(oPage);
				oApp.placeAt("content");		
			});			
			
		</script>

	</head>
	<body class="sapUiBody" role="application">
		<div id="content"></div>
	</body>
</html>

核心代码在 onFilterProducts 函数中:

  • oEvent.getParameter('query') 获取查询的值

  • var oBinding = oList.getBinding("items");获取 sap.ui.model.ListBinding对象,然后通过 oBinding.filter() 方法,向服务器提交请求,包含 $filter 查询参数,从而执行筛选。

取消筛选

用户在 SeachField 中清除筛选条件界面重新加载所有的产品,也就是取消筛选。原因在于当 aFilters 数组被清空,oBindingaFilters 属性为 null, filter() 方法就取消了筛选。

参考

filter method of sap.ui.model.binding

你可能感兴趣的:(SAPUI5)