如何从绑定到SAPUI5中元素的“上下文”中获取EDM类型?

问题描述

我有一个SAPUI5应用程序。

我通过如下的智能字段定义了一个元素:

<smartField:SmartField value="{GefahrInVerzug}" width="auto">
    <smartField:configuration>
        <smartField:Configuration preventinitialDataFetchInValueHelpDialog="false" displayBehavIoUr="descriptionOnly"/>
    </smartField:configuration>
</smartField:SmartField>

GefahrInVerzug字段在我的元数据中定义为布尔值:

<Property Name="GefahrInVerzug" Type="Edm.Boolean" sap:creatable="true" 
sap:updatable="true" sap:deletable="true" sap:label="Gefahr in Verzug"/>

假设我对呈现的控件的onInputChange事件具有以下处理程序:

onInputChange: function (oEvent) {
    var oField = oEvent.getSource(),oContext = oField.getBindingContext();
    //oContext.getEdmType();
}

如何通过访问元素(即Edm Type)或上下文对象(即oField)来获得oContext

在这种情况下,我正在寻找可以将Edm.Boolean返回给我的解决方案!

解决方法

我们可以在控制器中定义以下函数,以从字段中提取Edm Type

 // Returns a list that contains a map between 
 // UI5 elements' types and the property that contains the value!
 // Normally bound to the oData property 
 _getFieldTypeAttribute: function () {
    var aFieldTypes = {
        "sap.m.Input": "value","sap.m.Select": "selectedKey","sap.m.ComboBox": "selectedKey","sap.m.CheckBox": "selected","sap.m.DatePicker": "dateValue","sap.m.DateTimePicker": "value","sap.m.TextArea": "value","sap.m.Switch": "state","sap.ui.comp.smartfield.SmartField": "value"
    };
    return aFieldTypes;
},// Extract the EDM type from Metadata
_getEdmType: function(oField,sPropertyName){
    var regex = /\/([^(]+)/gm,oContext = oField.getBindingContext(),oModel = oContext.getModel(),oMetaModel = oModel.getMetaModel(),sBindingPath = oContext.getPath(),sType = null;
    //
    var aMatches = regex.exec(sBindingPath);
    if(aMatches.length > 0){
        var sSetName = aMatches[1],oEntitySet = oMetaModel.getODataEntitySet(sSetName),sEntityType = oEntitySet.entityType,oEntityType = oMetaModel.getODataEntityType(sEntityType),oProperty = oMetaModel.getODataProperty(oEntityType,sPropertyName);
            if (oProperty ) {
                sType = oProperty.type;
            }
    }
    //
    return sType;
},// Is fied when the input value is changed!
onInputChange: function (oEvent) {
    var oField = oEvent.getSource(),aFieldTypes = this._getFieldTypeAttribute(),sFieldType = oField.getMetadata().getName(),sFieldPath = oField.getBinding(aFieldTypes[sFieldType]).getPath(),sPropertyName = sFieldPath && sFieldPath.startsWith("/") ? sFieldPath.substring(1) : sFieldPath,sBindingPath = sPropertyName ? oContext.getPath() + "/" + sPropertyName : null; 
    console.log(this._getEdmType(oField,sPropertyName));
}

例如,当为布尔类型的元素触发此函数时,它将打印Edm.Boolean

,

Take a look here

onInputChange: function (oEvent) {
    var oField = oEvent.getSource(),sType = oContext.getProperty("/#EntityName/GefahrInVerzug/@type");
}

在元数据MaxLength中,类型使用大写字母表示,但使用该名称 您将无法获取元数据值。