This is about how to get a control by its ID from a fragment in a controller in SAPUI5.
It’s straightforward besides one pitfall.
Understand this pitfall and how to avoid it.
Let’s dive right in!
Get a Control by its ID from a fragment in an Controller in SAPUI5
The requirement is to get an SAPUI5 control by its ID from a fragment on a button click in a controller.
Actually, it is simple—but there is one pitfall:
There is an XML view with an embedded XML fragment:
<!-- in your XML view -->
...
<core:Fragment
id="fragment-1"
fragmentName="fragment1"
type="XML">
</core>
<Button
press="onPress"
text="Get text control!">
</Button>
...
And the XML fragment:
<!-- in your XML fragment -->
<core:FragmentDefinition
xmlns="sap.m"
xmlns:core="sap.ui.core">
<Text
id="text-1"
text="I'm a text."
</Text>
</core:FragmentDefinition>
Plus a controller:
// in your controller
...
onPress: function() {
var oText = {};
oText = this.byId("text-1");
sap.base.Log.info(oText); // returns undefined
}
...
this.byId(“text.1”) does not work—that is because the fragment has an id property in the XML view:
<!-- in your XML view -->
...
<core:Fragment
id="fragment-1"
<!-- here is the fragment id -->
fragmentName="fragment1"
type="XML">
</core>
<Button
press="onPress"
text="Get text control!">
</Button>
...
Sounds weird but it is how it is ¯\_(ツ)_/¯
this.byId(“text1”) does not work because if you give the fragment an ID on its own then the fragment gets prefixed not only with the view ID of the fragment’s view but with the ID of the fragment as well.
Plus, the IDs of the controls of a fragment only get generated by the view of the fragment if the fragment does not have an ID.
Long story short: that means if the fragment has no id property then this.byId(“text1) works:
<!-- in your XML view -->
...
<core:Fragment
fragmentName="fragmentName1"
type="XML">
</core>
...
But there is also an option to get a fragment even if it has an ID: If a fragment has an id property then it is possible to get
// in your controller
...
var sFragmentId = this.getView().createId("fragment-1");
var sControlId = "text-1";
var oText = sap.ui.core.Fragment.byId(sFragmentId, sControlId); // works
...
Now you know.