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

🏷️

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

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

So if you want to learn how to pass custom data from an XML view to its controller, then you’re 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 that by using the aggregation customData.

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

<!-- in your XML view -->

...

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

...

In the view’s controller method onPress, you could, for instance, get the id property (button-1) and the text property (Foo) 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 data from the button control to the method onPress?

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

It’s surprisingly simple to do this.

Here is how:

Almost every control in SAPUI5 has an aggregation customData.

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

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

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

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

</Button>

...

Now you can get 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
  oEvent.getSource().data("customDataKey");

}
 
...

See here for more on SAPUI5 custom data: What Is Custom Data and How to Use Custom Data in SAPUI5?

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

📚 More Articles

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