Adam Harkus
Adam Harkus

Reputation: 2210

How do I apply logic to binding aggregation in order to generate children dynamically

I have a table in SAPUI5, which works fine, displaying 5 cells of info.

However, how do I apply logic to this? For example, I sometimes need the 2nd cell to be a sap.m.RatingIndicator as opposed to sap.m.Text.

Is there a way to provide logic or must the cells always be hard-coded?

oTable.bindItems("/", new ColumnListItem({
  cells: [
    new HTML({ // sap/ui/core/HTML
      content: "<p style='margin:0'>{path: 'Sequence', type: 'sap.ui.model.odata.type.String', constraints: {isDigitSequence: true}}.  {QuestionDesc} - <strong>{CompetencyDesc}</strong></p>"
    }),
    new Text({ // sap/m/Text
      text: "{AnswerLabel} ({AnswerScore})",
      visible: true
    }),
    new Image({ // sap/m/Image
      src: "{SmileyUrl}",
      width: "2em"
    }),
    // ...
  ]
}));

Upvotes: 1

Views: 565

Answers (1)

Boghyon Hoffmann
Boghyon Hoffmann

Reputation: 18064

You can make use of a factory function.

<Table items="{
  path: '/',
  factory: '.createColumnListItem'
}" />
createColumnListItem: function(id, context/*of the current item*/) {
  const displayRatingIndicatorInstead = /*...*/;
  return new ColumnListItem(id, {
    cells: [
      // ...
      displayRatingIndicatorInstead ? new RatingIndicator() : new Text(),
      // ...
    ]
  });
},

In contrast to providing a template control, factory functions allow us to instantiate a new control dynamically for each iteration step.

For more information and examples, take a look at the documentation topic Using Factory Functions.


When using bindItems

oTable.bindItems({
  path: "/",
  factory: this.createColumnListItem.bind(this),
  // no template!
  // ...
});

From the API reference: ManagedObject#bindAggregation:

A factory function that will be called to create an object for each item in the aggregation; this is an alternative to providing a template object and can be used when the objects should differ depending on the binding context; the factory function will be called with two parameters:

  • An id that should be used for the created object, and
  • The binding context for which the object has to be created;

The function must return an object appropriate for the bound aggregation.

Upvotes: 1

Related Questions