首页 > 解决方案 > 如何从绑定到 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给我的解决方案!

标签: sapui5

解决方案


我们可以在控制器中定义以下函数以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(),
        oContext = oField.getBindingContext(),
        oModel = oContext.getModel(),
        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例如,当为布尔类型的元素触发此函数时,它会打印!


推荐阅读