SAPUI5: How to Pass Data from an XML View to Its Controller?

🏷️

This is about how to pass custom data from an XML view to its controller in SAPUI5.

You can pass additional data by the aggregation customData of almost every control

So if you want to learn how to pass custom data from an XML view to its controller, then you are in the right place.

Let’s get started!

How to Pass Custom Data From an XML View to Its Controller in SAPUI5?

If you want to pass custom data from an XML view to its controller in SAPUI5, you can do so by the aggregation customData.

For example, to pass custom data from a button to a press event of the button:

<!-- in your XML view -->

...

  <!-- how pass data to the controller? -->
  <Button
    id="button-1"
    text="{Foo}"
    press="onPress">
  </Button>

...

In the oEvent of the view’s controller method onPress you could retrieve, for example, the id (button-1) and text (Foo) properties of the button:

// in your controller
...


  onPressButton: function(oEvent) {
 
    // retrieve the button's id
    oEvent.getSource().getId();

    // retrieve the button's text
    oEvent.getSource().getText();

}
 
...

But what if you would like to pass other custom data from the XML view’s button control to the method onPress?

For example, another value than Foo from the OData model from the example above?

Here is how:

Every control in SAPUI5 has the aggregation customData.

The aggregation customData is originally implemented in the class Element of the SAPUI5 framework—every SAPUI5 control inherits from the class Element and therefore, features the aggregation customData.

The aggregation customData and its items CustomData can be set in an XML view:

<!-- in your XML view -->
...

<Button
  id="button-1"
  text="{Foo}"
  press="onPress">
  <customData>
      
    <core:CustomData
      key="{CustomDataKey1}"
      value="{CustomDataValue1}"
    </customData>

</Button>

...

Now you can retrieve the custom data in the view’s controller’s onPress method:

// in your controller
...
 
onPress: function(oEvent) {
 
  // retrieve the button's id
  oEvent.getSource().getId();

  // retrieve the button's text
  oEvent.getSource().getText();

  // retrieve the custom data value1
  oEvent.getSource().data("key1");

  // retrieve the custom data value2
  oEvent.getSource().data("key2");

}
 
...

Voila.

Apropos XML views: Learn here how to pass custom data from an XML view to a controller in SAPUI5.

🙌 More Articles

🔥 The Complete SAP ERP Modules Overview Infographic in PDF Format (Free)

Plus, don't miss future infographics and free SAP tips and insights that are available only to newsletter subscribers. 

Leave a Comment

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.
You need to agree with the terms to proceed

Menu