SAPUI5: What Is Custom Data and How to Use Custom Data?

Photo of author
By INUI
| Published on

This is how to use custom data in SAPUI5.

With custom data, you can add additional data to almost any SAPUI5 control.

So if you want to know how to use custom data in an XML view and controller, then you are in the right place.

Let’s get started!

Add More Values to an SAPUI5 Control With Custom Data

You can add custom data to almost any SAPUI5 control.

Imagine custom data as an extra text property of a control.

Only custom data can hold not just strings, but any kind of object.

However, you’ll mostly use it for strings or numbers from your model.

For example, a button has the property text.

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

<Button
  text="{text}"
  press="onPress"/>

...

But what if you want to add another value to the button so you can get it in the press event method in the controller? Like you want the button to hold an extra value from the model that you can process in the controller.

The button control doesn’t have another property where you can add your extra value.

That’s why almost every control has the aggregation customData. You can add as many CustomData controls to the aggregation as you want.

Each CustomData has a key and a value property.

The key is to get the value of a CustomData control.

Into the value property of the CustomData control goes whatever you want to add to the parent control of the customData aggregation.

You’ll see how that works below.

You can add custom data to a control in an XML view and a controller:

Add Custom Data to a Control in an XML View

First, add the customData aggregation and a CustomData control to the button control:

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

<Button
  text="{text}"
  press="onPress">
  <customData>
   
    <CustomData 
      key="extraValue" 
      value="{extraValue}"/>
  
  </customData>
</Button>

...

You could also add custoom data to the button in an XML view like this:

<!-- in your XML view -->
<mvc:View 
  xmlns:mvc="sap.ui.core.mvc"
  xmlns:customData="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1">

  <Button
    text="{text}"
    press="onPress"
    customData:extraValue="{extraValue}"/>

</mvc:View>

Then retrieve the CustomData control’s value in the onPress method in the view’s controller:

// in your controller
...
 
onPress: function(oEvent) {
 

  var oButton = oEvent.getSource();

  var sExtraValue = oButton.data("extraValue");

}
 
...

Add Custom Data to a Control in a Controller

To set custom data to a control in a controller is as easy as getting custom data from a control:

// in your controller
...

oButton.data("extraValue", "your extra value"); // first argument is the key, second is the value
 
...

Leave a Comment