SAPUI5 (28) - 基于 ODataModel 的排序和分组

OData 如何排序

OData 支持使用 $orderby 参数实现数据排序。排序的时候有两种顺序:升序 (asc) 和降序 (desc),默认是升序。我们以 Northwind OData 数据服务为例:

http://services.odata.org/V3/Northwind/Northwind.svc/Products?$orderby=ProductName

查询所有的产品,按 ProductName 排序。在浏览器中输入上面的请求,或者使用 Chrome 的插件 Postman , 可以查看服务器返回的数据。常用的排序参数:

  • 单字段排序,默认升序:/Products?$orderby=ProductName
  • 单字段排序,显式使用升序:/Products?$orderby=ProductName asc
  • 多字段排序, 产品名称升序,类别名称降序:/Products?$ordery=ProductName, Category/CategoryName desc

oDataModel 的实现数据排序

oDataModel 是服务器端模型,排序采用的方法是 sap.ui.model.ListBinding 对象的 sort() 方法触发向服务器端发送 http 请求,服务器端将排序后的数据返回给客户端显示。一般代码如下:

var oListBinding = xxx;
oListBinding.sort(aSorters);

oListBinding.sort() 方法的参数可以是一个 sap.ui.model.Sorter 对象,或者 sap.ui.model.Sorter 的数组。若为单个对象,表示按单一条件排序,如果为数组,表示按多个条件排序。接下来给出示例。要实现的功能如下图:

点击 “供应商ID” 和 “供应商名称”,对相应字段进行排序。因为代码全部放在同一个 html 文件中,所以只贴出 javascript 代码:

// 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);

// 定义两个 Sorter 对象,第二个参数表示是否 Descending
var oIDSorter = new sap.ui.model.Sorter("SupplierID", false);
var oNameSorter = new sap.ui.model.Sorter("CompanyName", false);

// 按 SupplierID 排序
var onSortByID = function(oEvent){
    oIDSorter.bDescending = !oIDSorter.bDescending;
    
    var oTable = sap.ui.getCore().byId("suppliersTable");
    var oListBinding = oTable.getBinding("items");              
    oListBinding.sort(oIDSorter);    
};

// 按 CompanyName 排序
var onSortByName = function(oEvent){
    oNameSorter.bDescending = !oNameSorter.bDescending;
    
    var oTable = sap.ui.getCore().byId("suppliersTable");
    var oListBinding = oTable.getBinding("items");              
    oListBinding.sort(oNameSorter);     
};      

sap.ui.getCore().attachInit(function(){     
    
    var oTable = new sap.m.Table("suppliersTable", {
        width: "auto",
        noDataText: "Loading...",                   
        
        // header toolbar
        headerToolbar: new sap.m.Toolbar({
            content: [
                new sap.m.Title({text: "供应商清单"}),
                new sap.m.ToolbarSpacer()
            ]
        }),
        
        // columns
        columns: [
            new sap.m.Column({
                header: new sap.m.Toolbar({
                    content: [
                        new sap.m.Text({text: "供应商ID"}),
                        new sap.m.Button({
                            icon: "sap-icon://sort",
                            press: onSortByID
                        })
                    ]
                })
            }),
            new sap.m.Column({
                header: new sap.m.Toolbar({
                    content: [
                        new sap.m.Text({text: "供应商名称"}),
                        new sap.m.Button({
                            icon: "sap-icon://sort",
                            press: onSortByName
                        })
                    ]
                })
            }),
            new sap.m.Column({
                header: new sap.m.Toolbar({ 
                    content: [new sap.m.Text({text: "城市"})]
                })
            }), 
            new sap.m.Column({
                header: new sap.m.Toolbar({
                    content: [new sap.m.Label({text: "国家"})]
                })
            }),
        ],
        
        // items
        items: {
            path: "/Suppliers",
            sorter: oIDSorter,                      
            template: new sap.m.ColumnListItem({
                cells: [
                    new sap.m.Text({text: "{SupplierID}"}),
                    new sap.m.Text({text: "{CompanyName}"}),
                    new sap.m.Text({text: "{City}"}),
                    new sap.m.Text({text: "{Country}"})
                ]
            })                      
        }
    });         
    
    var oApp = new sap.m.App({
        pages: [
            new sap.m.Page({
                title: "oDataModel 排序",
                content: [oTable]
            })  
        ]
    });
    
    oApp.placeAt("content");
});     

解释一下排序相关的代码:

  • 定义两个 sap.ui.model.Sorter对象,分别按 供应商ID供应商名称 进行升序排列:
var oIDSorter = new sap.ui.model.Sorter("SupplierID", false);
var oNameSorter = new sap.ui.model.Sorter("CompanyName", false);
  • 初始按 供应商ID 进行排序:
var oTable = new sap.m.Table("productTable", {
    ...
    items: {
        path: "/Suppliers",
        sorter: oIDSorter,                      
        template: new sap.m.ColumnListItem({
            cells: [
                ...
            ]
        })                      
    }
})
  • 如果用户点击 供应商ID 旁边的按钮,则对该字段进行排序:
// 按 SupplierID 排序
var onSortByID = function(oEvent){
    oIDSorter.bDescending = !oIDSorter.bDescending;
    
    var oTable = sap.ui.getCore().byId("suppliersTable");
    var oListBinding = oTable.getBinding("items");              
    oListBinding.sort(oIDSorter);    
};

按供应商名称排序类似。

在 Chrome 浏览器中运行,F12 查看 Network trace,每次排序都向服务器端发送一个 http 请求, Query String Parameter 为 $orderby= XXX:

客户端排序

oData Model是服务器端 Model,按 SAP Help, 不可以在客户端进行排序和筛选:

https://help.sap.com/saphelp_nw74/helpdata/en/e1/b625940c104b558e52f47afe5ddb4f/content.htm

The OData model enables binding of controls to data from OData services. The OData model is a server-side model: the dataset is only available on the server and the client only knows the currently visible rows and fields. This also means that sorting and filtering on the client is not possible. For this, the client has to send a request to the server. The OData model currently supports OData version 2.0.

但每一次排序或者筛选,都需要向服务器提交请求,导致性能比较低,所以 SAP 后来又支持 oData Model (v2) 在客户端的排序和筛选。通过设置 ListBinding 的 OperationMode 来实现。默认情况下,OperationMode 是服务器端模式。

将上面的代码稍作变更:

var oTable = new sap.m.Table("suppliersTable", {
    width: "auto",
    noDataText: "Loading...",   
    ... 

    items: {
        path: "/Suppliers",
        sorter: oIDSorter,
        parameters: {
                operationMode: sap.ui.model.odata.OperationMode.Client
        },
        template: new sap.m.ColumnListItem({
            cells: [...]
        })                      
    }       

再点击一下排序按钮,是不是快多了呢?

多字段排序

多字段排序,只需要 ListBinding.sort() 的参数为 Sorter 对象的数组即可。比如,下面的示例,在之前代码的基础上,按照国家+公司名的方式进行排序:

var oIDSorter = new sap.ui.model.Sorter("SupplierID", false);
var oNameSorter = new sap.ui.model.Sorter("CompanyName", false);
var oCountrySorter = new sap.ui.model.Sorter("Country", false);

var onMultipleSort = function(oEvent){
    var oTable = sap.ui.getCore().byId("suppliersTable");
        var oListBinding = oTable.getBinding("items");  
        oListBinding.sort([oCountrySorter, oNameSorter]);
}

数据分组

new sap.ui.model.Sorter(sPath, bDescending?, vGroup?, fnComparator?)

数据分组 (Grouping) 是一种特殊类型的排序,在 sap.ui.modelSorter 对象实例化时,第三个参数为 true 则,按这个排序的 Path 分组。也可以是一个函数,这个函数获取上下文 (Context) 的值,并按这个上下文的值进行分组。比如,oContext.getProperty("date").getYear() 实现按年度排序。

下面的示例在 UI 中增加一个按钮,点击的时候按国家进行分组,再次点击取消分组:

<!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>

        <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);
            
            // 定义两个 Sorter 对象,第二个参数表示是否 Descending
            var oIDSorter = new sap.ui.model.Sorter("SupplierID", false);
            var oNameSorter = new sap.ui.model.Sorter("CompanyName", false);
            
            // 按 SupplierID 排序
            var onSortByID = function(oEvent){
                oIDSorter.bDescending = !oIDSorter.bDescending;
                
                var oTable = sap.ui.getCore().byId("suppliersTable");
                var oListBinding = oTable.getBinding("items");              
                oListBinding.sort(oIDSorter);
            };
            
            // 按 CompanyName 排序
            var onSortByName = function(oEvent){
                oNameSorter.bDescending = !oNameSorter.bDescending;
                
                var oTable = sap.ui.getCore().byId("suppliersTable");
                var oListBinding = oTable.getBinding("items");              
                oListBinding.sort(oNameSorter);     
            };      
            
            // 按国家分组
            var onGroupByCountry = function(oEvent){
                var oButton = sap.ui.getCore().byId("groupByCountryBtn");
                var action; // 1: 执行分组; 2: 取消分组
                                
                if (oButton.getText()=="按国家分组"){
                    oButton.setText("取消分组");
                    action = 1;
                }else{
                    oButton.setText("按国家分组");
                    action = 2;
                }
                
                var aSorters = [];
                
                if (action == 1){
                    var vGroup = function(oContext) {
                        var name = oContext.getProperty("Country");
                        return {
                             key: name,
                             text: name
                        };
                    };
                    
                    var oCountrySorter = new sap.ui.model.Sorter("Country", false, vGroup);
                    aSorters.push(oCountrySorter);
                }
                
                // apply sort
                var oTable = sap.ui.getCore().byId("suppliersTable");
                var oListBinding = oTable.getBinding("items");              
                oListBinding.sort(aSorters);    
            };
            
            sap.ui.getCore().attachInit(function(){     
                
                var oTable = new sap.m.Table("suppliersTable", {
                    width: "auto",
                    noDataText: "Loading...",                   
                    
                    // header toolbar
                    headerToolbar: new sap.m.Toolbar({
                        content: [
                            new sap.m.Title({text: "供应商清单"}),
                            new sap.m.ToolbarSpacer(),
                            new sap.m.Button({
                                id: "groupByCountryBtn",
                                text: "按国家分组",
                                press: onGroupByCountry
                            })
                        ]
                    }),
                    
                    // columns
                    columns: [
                        new sap.m.Column({
                            header: new sap.m.Toolbar({
                                content: [
                                    new sap.m.Text({text: "供应商ID"}),
                                    new sap.m.Button({
                                        icon: "sap-icon://sort",
                                        press: onSortByID
                                    })
                                ]
                            })
                        }),
                        new sap.m.Column({
                            header: new sap.m.Toolbar({
                                content: [
                                    new sap.m.Text({text: "供应商名称"}),
                                    new sap.m.Button({
                                       icon: "sap-icon://sort",
                                       press: onSortByName
                                    })
                                ]
                            })
                        }),
                        new sap.m.Column({
                            header: new sap.m.Toolbar({ 
                                content: [new sap.m.Text({text: "城市"})]
                            })
                        }), 
                        new sap.m.Column({
                            header: new sap.m.Toolbar({
                                content: [new sap.m.Label({text: "国家"})]
                            })
                        }),
                    ],
                    
                    // items
                    items: {
                        path: "/Suppliers",
                        sorter: oIDSorter,
                        parameters: {
                              operationMode: sap.ui.model.odata.OperationMode.Client
                        },
                        template: new sap.m.ColumnListItem({
                            cells: [
                                new sap.m.Text({text: "{SupplierID}"}),
                                new sap.m.Text({text: "{CompanyName}"}),
                                new sap.m.Text({text: "{City}"}),
                                new sap.m.Text({text: "{Country}"})
                            ]
                        })                      
                    }
                });         
                
                var oApp = new sap.m.App({
                    pages: [
                        new sap.m.Page({
                            title: "oDataModel 排序和分组",
                            content: [oTable]
                        })  
                    ]
                });
                
                oApp.placeAt("content");
            });         
            
        </script>

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

按国家分组的关键代码如下:

// 按国家分组
var onGroupByCountry = function(oEvent){
    var oButton = sap.ui.getCore().byId("groupByCountryBtn");
    var action; // 1: 执行分组; 2: 取消分组
                    
    if (oButton.getText()=="按国家分组"){
        oButton.setText("取消分组");
        action = 1;
    }else{
        oButton.setText("按国家分组");
        action = 2;
    }
    
    var aSorters = [];
    
    if (action == 1){
        var vGroup = function(oContext) {
            var name = oContext.getProperty("Country");
            return {
                    key: name,
                    text: name
            };
        };
        
        var oCountrySorter = new sap.ui.model.Sorter("Country", false, vGroup);
        aSorters.push(oCountrySorter);
    }
    
    // apply sort
    var oTable = sap.ui.getCore().byId("suppliersTable");
    var oListBinding = oTable.getBinding("items");              
    oListBinding.sort(aSorters);    
};

源代码

28_zui5_odata_filter_sort_group

References

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容