SAPUI5 (18) - 数据显示格式设定
阅读原文时间:2021年04月20日阅读:1

在sapui5中,除了使用数据类型来帮助在UI中设定显示格式外,还可以使用formatter。本篇介绍设置数据显示格式的4种方法。

  • 在Constructor或绑定方法中定义formatter
  • 在Controller中定义formatter
  • 在专门模块中定义formatter
  • 自定义数据类型中设置formatter

在Constructor或绑定方法中定义formatter

假设我们在页面中显示产品信息,对于产品名称,我们想将产品名称以大写显示。怎么实现呢?首先看一种最简单的方法,在Constructor中定义formatter:

var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({
    productid: "10000",
    productname: "Micro Projector"
});
sap.ui.getCore().setModel(oModel);

var oText = new sap.m.Text({
    text: {
        path: "/productname",
        formatter: function(sValue){
            return sValue && sValue.toUpperCase();
        }
    }
});
oText.placeAt("content");

或者在绑定方法中定义:

var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({
    productid: "10000",
    productname: "Micro Projector"
});
sap.ui.getCore().setModel(oModel);

var oText = new sap.m.Text();
oText.bindProperty("text", "/productname", function(sValue){
    return sValue && sValue.toUpperCase();
});
oText.placeAt("content");

在controller中定义formatter

上面的方法简单是简单,但不利于复用。为了提高代码的复用性,我们可以将代码放在其它地方,比如放在controller中、放在专门的文件中。先来看如何将代码放在controller中。代码的文件结构如下:

index.html代码:

<!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"
                data-sap-ui-xx-bindingSyntax="complex"
                data-sap-ui-resourceroots='{"webapp": "./webapp"}' >
        </script>

        <script>
            var oApp = new sap.m.App({
                initialPage: "firstView"
            });
            var oView = sap.ui.xmlview({
                id: "firstView",
                viewName: "webapp.view.productInfo"
            });

            oApp.addPage(oView);
            oApp.placeAt("content");
        </script>

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

注意data-sap-ui-xx-bindingSyntax必须为complex。

productInfo.controller.js:

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/ui/model/json/JSONModel"
], 

function(Controller, JSONModel){
    "use strict";

    return Controller.extend("webapp.controller.productInfo", {
        // initialization
        onInit: function(){
            var oModel = new sap.ui.model.json.JSONModel();
            oModel.setData({
                productid: "10000",
                productname: "Micro Projector"
            });
            this.getView().setModel(oModel);
        },

        // convert to upper case
        toUpper: function(sValue){
            return sValue && sValue.toUpperCase();
        }
    });
});

在controller中定义toUpper()函数,将字符串转换成大写:

        toUpper: function(sValue){
            return sValue && sValue.toUpperCase();
        }

productInfo.view.xml代码:

<core:View xmlns:core="sap.ui.core" 
           xmlns:mvc="sap.ui.core.mvc" 
           xmlns="sap.m"
           controllerName="webapp.controller.productInfo" 
           xmlns:html="http://www.w3.org/1999/xhtml">
    <Page id="page" title="产品信息">
        <content>
            <Text text="{path: '/productname', formatter: '.toUpper'}"/>
        </content>
    </Page>
</core:View>

申明一个sap.m.Text控件,text属性中path绑定productname,formater为刚才定义的toUpper()函数。注意:toUpper前面的点号表示在当前controller中查找toUpper()方法

在专门模块中定义formatter

也可以将formatter放在专门的文件中,实现更大程度的复用。对上面的代码进行重构,代码文件结构变更如下:

index.html文件没有任何变化。将formatter.js放在model文件夹中,是因为formatter与数据相关。formatter.js的代码如下:

sap.ui.define([],

    function(){
        "use strict";

        return {
            toUpper: function(sValue){
                return sValue && sValue.toUpperCase();
            }
        };
    }
);

productInfo.controller.js:

sap.ui.define([
     "sap/ui/core/mvc/Controller",
     "sap/ui/model/json/JSONModel",
     "webapp/model/formatter",
], 

function(Controller, JSONModel, formatter){
        "use strict";

        return Controller.extend("webapp.controller.productInfo", {

            formatter: formatter,     

            // initialization
            onInit: function() {
                // application data
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({
                    productid: "10000",
                    productname: "Micro Projector"
                }); 

                // binding model to view
                this.getView().setModel(oModel);
            }  
        });
    }
);

在依赖的模块中添加webapp/model/formatter,并且指定formatter为formatter模块:formatter: formatter

productInfo.view.xml将formatter变更为:.formatter.toUpper:

<core:View xmlns:core="sap.ui.core" 
           xmlns:mvc="sap.ui.core.mvc" 
           xmlns="sap.m"
           controllerName="webapp.controller.productInfo" 
           xmlns:html="http://www.w3.org/1999/xhtml">
    <Page id="page" title="产品信息">
        <content>
            <Text text="{path: '/productname', formatter: '.formatter.toUpper'}"/>
        </content>
    </Page>
</core:View>

自定义数据类型中设置formatter

这里假定另外一个场景,为了对电话号码进行校验和显示,我们自定义一个phone number数据类型, 出于演示目的,只考虑手机号码,将手机号码按照13x-xxxx-xxxx这种方式分割显示并且对输入进行校验。代码文件结构如下:

index.html文件同上例,没有变化。

types.js:

sap.ui.define(        
    ["sap/ui/model/SimpleType"], 

    function(SimpleType){
        "use strict";

        return {
            PhoneNumber: SimpleType.extend("stonetest.phoneNumber", {
                // formatter
                formatValue: function(sValue){
                    sValue = sValue.replace(/-/g, "");
                    if (sValue.substr(0, 1) == "1") {// 第一个字符为1,手机号码
                        return sValue.substr(0,3) + "-" + sValue.substr(3,4)
                            + "-" + sValue.slice(7);
                    }
                },

                // parse value
                parseValue: function(oValue){
                    return oValue;
                },

                // validation
                validateValue:function(sValue){
                    sValue = sValue.replace(/-/g, "");
                    if (!/^1[3|4|5|8][0-9]\d{4,8}$/.test(sValue)){
                        throw new sap.ui.model.ValidateException("手机号码格式错误!");
                    }
                }
            })
        }     
    }
);

phoneNumber数据类型继承自sap.ui.model.SimpleType,每一个simpleType都有formatValue, parseValue和ValidateValue三个方法,实现formatValue和ValidateValue。

productInfo.controller.js:

sap.ui.define([
     "sap/ui/core/mvc/Controller",
     "sap/ui/model/json/JSONModel",
     "webapp/model/types",
], 

function(Controller, JSONModel, types){
        "use strict";

        return Controller.extend("webapp.controller.productInfo", {

            types: types,     

            // initialization
            onInit: function() {
                // application data
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({
                    productid: "10000",
                    productname: "Micro Projector",
                    phone:"13612345678"
                }); 

                var oView = this.getView();

                // binding model to view
                oView.setModel(oModel);                     

                sap.ui.getCore().getMessageManager().registerObject(oView, true);
            }  
        });
    }
);

在依赖模块中添加webapp/model/types模块,并指定types为依赖的types模块。使用messageManager管理数据校验。

最后,在view中,使用定义的phoneNumber数据类型(productInfo.view.xml):

<core:View xmlns:core="sap.ui.core" 
           xmlns:mvc="sap.ui.core.mvc" 
           xmlns="sap.m"
           controllerName="webapp.controller.productInfo" 
           xmlns:html="http://www.w3.org/1999/xhtml">
    <Page id="page" title="产品信息">
        <content>
            <Text text="{/productname}"/>
            <Input value ="{path:'/phone', type:'.types.PhoneNumber'}" />           
        </content>
    </Page>
</core:View>