Qualiture
Qualiture

Reputation: 4920

How to dynamically load an XML fragment in XML view?

Suppose I have the following XML view:

<mvc:View xmlns:mvc="sap.ui.core.mvc" ...>
    <Page>
        <content>
            <l:VerticalLayout>
                <l:content>
                    <core:Fragment fragmentName="my.static.Fragment" type="XML" />
                </l:content>
            </l:VerticalLayout>
        </content>
    </Page>
</mvc:View>

The fragment my.Fragment is statically loaded. However, I now want to dynamically change the to-be-loaded fragment (ideally using data binding the fragmentName property, but any other means should be ok as well), ie. something like this:

<mvc:View xmlns:core="sap.ui.core.mvc" ...>
    <Page>
        <content>
            <l:VerticalLayout>
                <l:content>
                    <core:Fragment fragmentName="{/myDynamicFragment}" type="XML" />
                </l:content>
            </l:VerticalLayout>
        </content>
    </Page>
</mvc:View>

However, the latter does not work, and the Fragment definitions don't allow for data binding... I might have missed something, but how should I dynamically change the Fragment in my XML view based on a parameter/model property/etc?

For now, I have resorted to a custom control instead of directly using a fragment in my view, and have that control do the dispatching to the appropriate Fragment, but I feel there should be an easier, out-of-the-box way...

Upvotes: 7

Views: 29411

Answers (2)

adirocks27
adirocks27

Reputation: 141

The fragment name can also result from a binding, including an expression binding which evaluates to a constant. As formatter functions return strings, and not booleans, === 'true' has been added in the following example:

Example: Dynamic Fragment Name

<core:Fragment fragmentName="{= ${path: 'facet>Target', formatter: 'sap.ui.model.odata.AnnotationHelper.isMultiple'} === 'true'
    ? 'sap.ui.core.sample.ViewTemplate.scenario.TableFacet'
    : 'sap.ui.core.sample.ViewTemplate.scenario.FormFacet' }" type="XML"/>

Upvotes: -3

Nikolay Nadorichev
Nikolay Nadorichev

Reputation: 901

I think the only solution will be initialization of fragment from onInit method of controller:

sap.ui.controller("my.controller", {
    onInit : function(){
        var oLayout = this.getView().byId('mainLayout'), //don't forget to set id for a VerticalLayout
            oFragment = sap.ui.xmlfragment(this.fragmentName.bind(this));
        oLayout.addContent(oFragment);
    },

    fragmentName : function(){
       return "my.fragment";
    }
});

Upvotes: 4

Related Questions