如何通过 ID 访问 XML 片段中的元素

问题描述:

我正在开发 SAPUI5 应用程序.我有一个 XML 视图,其中包含一个 XML Fragment和一个按钮来保存.

I am working on a SAPUI5 application. I have an XML view which contains an XML Fragment and a Button to save.

片段包含一些控件,如下拉菜单、文本字段和表格.当我按下保存按钮时,我需要获取表中的所有行并调用 OData 更新服务.

The fragment contains a few controls like drop-down, text field and a table. When I press on the save button, I need to get all the rows in the table and call an OData update service.

问题出在视图控制器中的 onSave 方法中.使用表的 ID 访问表时出错.任何人都可以帮助我并建议我如何通过控制器中的 ID 访问片段中使用的控件?

The problem is in the onSave method in view controller. I get an error while accessing the table using its ID. Can anyone help me and advice how can I access controls used in fragments by their ID in the controller?

这是代码片段:

查看:

<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns:core="sap.ui.core" xmlns:form="sap.ui.layout.form" xmlns="sap.m">
    <Page>
        ...
        <form:SimpleForm>
            <core:Fragment id ="fr1" fragmentName="first" type="XML" />
            <Button id="id1" press="onSave" />
        </form:SimpleForm>
    </Page>
</mvc:View>

片段定义:

<core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core">
    <Table id="tab1" mode="MultiSelect">
        ...
    </Table>
</core:FragmentDefinition>

控制器:

sap.ui.controller("view", {
    onSave: function() {
        //var tab = this.getView().byId("tab1"); // Not working
        var tab  = sap.ui.getCore().byId("tab1"); // Not working
    },
    // ...
});

查看 GitHub 上的 OpenUI5 代码,如果 本身没有有明确的 ID.

Looking at the OpenUI5 code at GitHub, it seems that the Fragment delegates the local ID generation to the containing view if the <Fragment/> itself does not have an explicit ID.

所以你的代码 this.getView().byId("tab1") 应该在你从你的 元素.

So your code this.getView().byId("tab1") should work as soon as you remove the id="fr1" attribute from your <Fragment/> element.

当使用显式 ID 时,有一个 静态Fragment.byId 方法来检索控件.我想你必须像这样使用它:

When using explicit IDs there is a static Fragment.byId method to retrieve the control. I guess you have to use it like this:

// Fragment required from "sap/ui/core/Fragment"
var fragmentId = this.getView().createId("fr1");
var tab = Fragment.byId(fragmentId, "tab1");