UI5
No Comments

How to Get a Control by ID from an XML Fragment in SAP UI5?

Banana cut into pieces.

In this example, it is the aim to get a control in a controller by its ID from a fragment on a button click. Actually, it is simple. But there is one pitfall.

There is an XML view with an embedded XML fragment …

<!-- in your XML view -->

<mvc:View 
   height="100px"
   controllerName="app.controller1"
   xmlns="sap.m"
   xmlns:mvc="sap.ui.core.mvc">

     <core:Fragment 
       id="fragment1"
       fragmentName="fragmentName1"
       type="XML">
     </core>

     <Button
       press="onButtonPress"
       text="Get text control!">
     </Button>

 </mvc:View>

… and the XML fragment itself …

<!-- in your XML fragment -->

<core:FragmentDefinition
  xmlns="sap.m"
  xmlns:core="sap.ui.core">

  <Text
    id="text1"
    text="Text_1"
  </Text>

</core:FragmentDefinition>

… and a controller …

// in your controller

sap.ui.define([ 
  "sap/ui/core/mvc/Controller",
  "sap/m/MessageToast"
], function (Controller, MessageToast) { 
  "use strict"; 

  return Controller.extend("app.controller1", { 

    onButtonPress: function() {
  
      var oText = {};

      oText = this.byId("text1"); // does not work

      console.log(oText); // Undefined

    }

  });

});

Then this.byId(“text1”) does not work. That is because the fragment has an id property:

<!-- in your XML view -->

...

<core:Fragment 
  id="fragment1" <!-- id property -->
  fragmentName="fragmentName1"
  type="XML"> 
</core>

...

Sounds weird but it is how it is. this.byId(“text1”) does not work because 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. 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 a control from the fragment by the method sap.ui.core.Fragment.byId:

// in your controller

...

var sFragmentId = this.getView().createId("fragment1");
var sControlId = "text1";

var oText = sap.ui.core.Fragment.byId(sFragmentId, sControlId); // works

...

Most Recent Articles

Will SAP UI5 replace the SAP Web UI?

SAP Full Forms

More Similar Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu