How to dynamically load an XML fragment in XML view? - sapui5

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...

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";
}
});

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"/>

Related

The scrollToSection method does not scroll

I have a ObjectPageLayout that is divided two sections, that it looks like:
<Page id="floatingFooterPage" enableScrolling="false" showNavButton="true" navButtonPress="onNavButtonPress">
<content>
<uxap:ObjectPageLayout id="ClassDetail" showHeaderContent="true">
<uxap:headerTitle>
<uxap:ObjectPageHeader></uxap:ObjectPageHeader>
</uxap:headerTitle>
<uxap:headerContent>
<f:SimpleForm editable="false" layout="ResponsiveGridLayout" singleContainerFullSize="false">
<f:content>
<Label text="{i18n>charsClass}"/>
<Text text="{ClassInfo>/classNum} {ClassInfo>/classNumDescr}"/>
<Label text="{i18n>charsClassType}"/>
<Text text="{ClassInfo>/classType} {ClassInfo>/classTypeText}"/>
</f:content>
</f:SimpleForm>
</uxap:headerContent>
<uxap:sections>
<uxap:ObjectPageSection title="{i18n>charsCharsSel}" id="SecChars">
<uxap:subSections>
<uxap:ObjectPageSubSection >
<uxap:blocks>
<mvc:XMLView width="100%" viewName="ch.mindustrie.ZMM_OBJECTS_CLASSES.view.CharacSelection" id="CharacSelection"/>
</uxap:blocks>
</uxap:ObjectPageSubSection>
</uxap:subSections>
</uxap:ObjectPageSection>
<uxap:ObjectPageSection title="{i18n>charsObject}" id="SecObject">
<uxap:subSections>
<uxap:ObjectPageSubSection >
<uxap:blocks>
<mvc:XMLView width="100%" viewName="ch.mindustrie.ZMM_OBJECTS_CLASSES.view.ObjectTable" id="ObjectTable"/>
</uxap:blocks>
</uxap:ObjectPageSubSection>
</uxap:subSections>
</uxap:ObjectPageSection>
<!-- <uxap:ObjectPageSection title="Sub classes" id="SecSub" visible="false">
<uxap:subSections>
<uxap:ObjectPageSubSection >
<uxap:blocks>
<mvc:XMLView width="100%" viewName="ch.mindustrie.ZMM_OBJECTS_CLASSES.view.ClassTree" id="SubTree"/>
</uxap:blocks>
</uxap:ObjectPageSubSection>
</uxap:subSections>
</uxap:ObjectPageSection>-->
</uxap:sections>
</uxap:ObjectPageLayout>
</content>
<footer>
<Toolbar>
<ToolbarSpacer/>
<Button id="FindObject" text="{i18n>charsObject}" press="onPress" type="Transparent"/>
</Toolbar>
</footer>
</Page>
I wanted to scroll to section SecChars programmatically and I have done as following:
_scrollToObjectSection: function () {
const oObjPage = this.byId("ClassDetail");
oObjPage.scrollToSection("SecObject", 0, 0);
}
But it does not work at all. What am I doing wrong?
Issues
The API scrollToSection awaits a global ID (the suffix "SecObject" alone is not enough). So it should be:
oObjPage.scrollToSection(this.byId("SecObject").getId());
That API, however, can be only successfully performed when the DOM of the ObjectPageLayout is fully ready. I added "fully" because calling scrollToSection within the onAfterRendering event delegate won't do anything either. There must be an additional timeout of about 450 ms. It's nowhere documented though how many milliseconds are actually required, and there is no public event for this case either.
Alternatives
Use setSelectedSection instead, as mentioned in the documentation topic Object Page Scrolling. The ObjectPageLayout will scroll to that section, but currently without any scrolling animation (iDuration = 0). The "selectedSection" is an association, hence, it can be also set within the view definition:
<uxap:ObjectPageLayout selectedSection="mySection">
<uxap:ObjectPageSection id="mySection">
Keep using scrollToSection but leverage the ⚠️ private event "onAfterRenderingDOMReady"(src) which is fired when the DOM is fully ready:
onInit: function() {
// ...
this.scrollTo(this.byId("mySection"), this.byId("myObjectPageLayout"));
},
scrollTo: function(section, opl) {
const id = section.getId();
const ready = !!opl.getScrollingSectionId(); // DOM of opl is fully ready
const fn = () => opl.scrollToSection(id);
return ready ? fn() : opl.attachEventOnce("onAfterRenderingDOMReady", fn);
},
The API getScrollingSectionId() returns a falsy value (currently "") if the DOM is not fully ready.

Executing a function based on a click event on an html element in SAPUI5

Hi I'm trying to get a function defined in my controller to execute when I press on a specific area of a picture. I'm using an html map to define the areas of my picture (code below)
<mvc:View id="Main" controllerName="Demo.picture.controller.Main" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc"
displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core">
<App id="idAppControl">
<pages>
<Page title="{i18n>title}">
<content>
<Image src = "Some image source" alt="Image" useMap="Map"/>
</content>
</Page>
</pages>
</App>
<html:map name="Map" id="Map">
<html:area id= "area_1" shape="rect" coords= "0,0,240,215" alt="Chart" onclick="???"/>
<html:area id = "area_2" shape="rect" coords="240,0,480,215" alt="Start" onclick="???"/>
</html:map> </mvc:View>
Not sure if using onclick is the right way of doing this.
Controller code:
sap.ui.define([
"sap/ui/core/mvc/Controller"], function (Controller) {
"use strict";
return Controller.extend("Demo.picture.controller.Main", {
SomeMethodFoo: function () {
"method to be executed when area_1 is pressed"
},
SomeMethodGoo: function () {
"method to be executed when area_2 is pressed"
}
});});
Is it possible to attach an eventHandler for a onclick event to these areas? Or is there some other way to do this?
I guess that it would be something like this:
onclick="sap.ui.getCore().byId('__xmlview0').getController().SomeMethodFoo()"
but your need to manage yourself to know your view ID, which won't be always '__xmlview0'

Page Is Blank Without Throwing Any Errors

I am trying to display few tiles in a tile container which fetches data from a dummy JSON file. I have coded exactly shown in this sample. But my page appears empty. Also it doesn't show any errors in the console. Below are the snippets of my code.
View1.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
return Controller.extend("AdminMovie.controller.View1", {
});
});
View1.view.xml
<mvc:View
displayBlock="true"
controllerName="AdminMovie.controller.View1"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
>
<Page showHeader="false" enableScrolling="false">
<mvc:XMLView viewName="AdminMovie.view.TileContainer"/>
<footer>
<OverflowToolbar id="otbFooter">
<ToolbarSpacer/>
<Button type="Accept" text="Add New Movie"/>
</OverflowToolbar>
</footer>
</Page>
</mvc:View>
TileContailner.view.xml
<mvc:View
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
controllerName="AdminMovie.controller.TileContainer"
>
<App>
<pages>
<Page
showHeader="false"
enableScrolling="false"
title="Stark"
>
<TileContainer id="container"
tileDelete="handleTileDelete"
tiles="{/MovieCollection}"
>
<HBox>
<StandardTile
icon="{icon}"
type="{type}"
number="{number}"
numberUnit="{numberUnit}"
title="{title}"
info="{info}"
infoState="{infoState}"
/>
</HBox>
</TileContainer>
<OverflowToolbar>
<Toolbar>
<ToolbarSpacer/>
<Button
text="Edit"
press=".handleEditPress"
/>
<ToolbarSpacer/>
</Toolbar>
</OverflowToolbar>
</Page>
</pages>
</App>
</mvc:View>
TileContainer.js
sap.ui.define([
"jquery.sap.global",
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel"
], function(jQuery, Controller, JSONModel) {
"use strict";
return Controller.extend("AdminMovie.controller.TileContainer", {
onInit: function(evt) {
// set mock model
var sPath = jQuery.sap.getModulePath("AdminMovie", "/MovieCollection.json");
var oModel = new JSONModel(sPath);
this.getView().setModel(oModel);
},
handleEditPress: function(evt) {
var oTileContainer = this.byId("container");
var newValue = !oTileContainer.getEditable();
oTileContainer.setEditable(newValue);
evt.getSource().setText(newValue ? "Done" : "Edit");
},
handleTileDelete: function(evt) {
var tile = evt.getParameter("tile");
evt.getSource().removeTile(tile);
}
});
});
Cause
The root view is missing a root control or the height of the parent HTML elements is not set to 100%. The child elements cannot be rendered in full size.
Resolution
For Standalone or Top-Level Applications
Add sap.m.App (or sap.m.SplitApp in case of a master-detail layout) once in the entire application project to your root view:
<!-- Root view (typically "App.view.xml") -->
<mvc:View controllerName="..."
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
displayBlock="true"
>
<App id="topLevelApp"> <!-- Not in any other views! -->
<pages>
<!-- ... -->
</pages>
</App>
</mvc:View>
Root controls such as sap.m.App, sap.m.SplitApp, and sap.m.Shell write:
a bunch of properties into the header of the HTML document e.g. the viewport meta tag via sap/ui/util/Mobile.init.
height: 100% to all its parent elements by default (unless isTopLevel is disabled). src
The reason why the linked sample is working, is that the control sap.m.App was already added in index.html. The samples shown in the Demo Kit, however, often miss index.html in the code page to be shown which can be confusing.
For Nested or Embedded Applications
If you're developing an app that is to be rendered within an an existing app, keep in mind that the top-level app might come already with one root control (sap.m.App with isTopLevel enabled or sap.m.SplitApp) in its root view. I.e. in this case:
Add height="100%" to the View node of the root view definition, and
Either use <App isTopLevel="false"> or replace the <App> with <NavContainer>.
<!-- Root view (typically "App.view.xml") -->
<mvc:View controllerName="..."
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
displayBlock="true"
height="100%"
> <!-- ↑ Set height="100%" -->
<App isTopLevel="false"> <!-- or:
<NavContainer> if the UI5 version is below 1.91 -->
<pages>
<!-- ... -->
</pages> <!--
</NavContainer> -->
</App>
</mvc:View>
Otherwise, not using the isTopLevel="false" will cause the footer area of the embedded app to be pushed out of the viewport. This is a common issue e.g. for the views that are intended to extend the standard SAP Fiori app "My Inbox" since the app already contains one root control as a top-level UI element. Refer to SAP KBA #3218822.
⚠️ For other readers: if you're not using a TileContainer, see my previous answer for general solutions → https://stackoverflow.com/a/50951902/5846045
Causes for empty TileContainer
Unexpected child control
Besides the missing root control, the <TileContainer> in your code contains a list of HBoxes.
<TileContainer>
<HBox> <!-- ❌ Wrong aggregation child! -->
<StandardTile />
The default aggregation of TileContainer is, however, a control that is derived from sap.m.Tile.
Hence, you should be getting the following error message in the browser console:
Uncaught Error: "Element sap.m.HBox#__hbox1" is not valid for aggregation "tiles" of Element sap.m.TileContainer#__xmlview1--container
Please, remove the <HBox> as the binding template:
<TileContainer>
<StandardTile /> <!-- ✔️ -->
TileContainer contains only one Tile
There was a bug (issue #1813) in the TileContainer which failed making the aggregation visible in Chrome (works in Firefox) if there was only a single Tile. The fix is delivered with OpenUI5 version 1.56+, 1.54.2+, 1.52.8+, 1.50.9+, 1.48.19+, and 1.46.2+.

InteractiveBarChart: How to Bind Model

I can't find any example about binding a JSON model to an InteractiveBarChart in an XML view.
My view is the following:
<core:View
xmlns:core="sap.ui.core"
xmlns:m="sap.m"
xmlns="sap.f"
xmlns:f="sap.f"
xmlns:smartFilterBar="sap.ui.comp.smartfilterbar"
xmlns:mc="sap.suite.ui.microchart"
xmlns:layout="sap.ui.layout"
xmlns:customData="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1"
controllerName="webui.controller.Logger.HomeLogger"
height="100%"
>
<DynamicPage id="dynamicPage"
navButtonPress="onNavBack"
showNavButton="true"
>
<title>
<f:DynamicPageTitle>
<f:heading>
<m:Title text="Methode Logger" />
</f:heading>
<f:expandedContent>
<m:Text text="System analysis" />
</f:expandedContent>
<f:actions>
<m:ToolbarSpacer />
<m:Button
icon="sap-icon://action-settings"
binding="{securitySystem>/}"
press="onSettingsPress"
visible="{securitySystem>enabledApplications/enableSettingsAdmin}"
/>
</f:actions>
</f:DynamicPageTitle>
</title>
<header>
<DynamicPageHeader>
<content>
<layout:Grid defaultSpan="XL6 L6 M6 S12">
<m:FlexBox
width="20rem"
height="10rem"
alignItems="Center"
class="sapUiSmallMargin"
>
<m:items>
<mc:InteractiveBarChart
labelWidth="25%"
selectionChanged="chartSelectionChanged"
press="press"
bindBars="{/}"
>
<mc:bars>
<mc:InteractiveBarChartBar
label="{key}"
value="{value}"
/>
</mc:bars>
</mc:InteractiveBarChart>
</m:items>
</m:FlexBox>
</layout:Grid>
</content>
</DynamicPageHeader>
</header>
</DynamicPage>
</core:View>
I've to bind the InteractiveBarChart to my model, an array set in the controller. By SAP reference, I've to use bindBars method, but I can't make it work.
Any control in UI5 has the same concepts of data binding: property and aggregation bindings.
If control is aimed to show multiple things (i.e. table or list), it will have the so called aggregation.
In InteractiveBarChart control there is an aggregation "bars".
Any control can be bound against model via the unified binding syntax.
For programmatic binding is the following template: "bind{NAME OF AGGREGATION}". So in this case it will be "bindBars" method, which takes the same list of arguments as any aggregation binding;
For declaration binding in XML, you have to do 2 things:
tell the control about data source. In your case you should set the control's property with the name of aggregation "bars" to the binding string "{/}", in case you store the raw array in the root property of a default model (i.e. model without name)
define a template, which will be used as a basis of creation of a list of bars (you've already done it correctly)

How I can set the value of element of a fragment?

This is my fragment,
The fragment not have a controller
<core:FragmentDefinition
xmlns="sap.m"
xmlns:core="sap.ui.core">
<Dialog
title="Invio report via mail">
<content>
<FlexBox
alignItems="Start"
justifyContent="Center">
<items>
<TextArea id="idMailReport" value="themail.mail.it" rows="1" cols="50" />
</items>
</FlexBox>
</content>
<beginButton>
<Button text="Ok" press="onDialogOkButton" />
</beginButton>
<endButton>
<Button text="Close" press="onDialogCloseButton" />
</endButton>
</Dialog>
</core:FragmentDefinition>
Ho I can set che value of TextArea element?
I try to set it from a controller where I call the fragment:
var dialogFrafment = sap.ui.xmlfragment(
"dialogFragment",
"appIntra.fragment.dialog",
this // associate controller with the fragment
);
this.getView().addDependent(dialogFrafment);
dialogFrafment.open();
this.byId("idMailReport").setValue("initial.mail.com");
Can you help me?
please try
sap.ui.getCore().byId("idMailReport").setValue("initial.mail.com");
it should work.
Here is the official document.
I solve it!
var dialogFrafment = sap.ui.xmlfragment(
"appIntra.fragment.dialog",
this.getView().getController() // associate controller with the fragment
);
my problem is that i had set a name of a fragment: "dialogFragment"
Whitout it all work! ;)
A bit outdated, but might be useful for others. When you reuse your fragment inside a view, giving it unique id like:
var dialogFrafment = sap.ui.xmlfragment(
"dialogFragment", // this is fragment's ID
"appIntra.fragment.dialog",
...
);
retrieving id of your nested control goes like:
this.byId(sap.ui.getCore().Fragment().createId("dialogFragment", "idMailReport"));
That way, your prepend fragment's id to your control's id.