Roman
Roman

Reputation: 61

sap.m.MultiComboBox: How to get texts from all selected items?

After selectionFinish, I would like to get all the selected item texts from the list. The usual approach of getting all the selected items goes like this:

this.byId("idExampleMultiComboBox").getSelectedItems();

Issue: It returns objects of type sap.ui.core.Item with all the aggregations/associations. I only need the text of the selected option.

MultiComboBox:

<MultiComboBox id="idExampleMultiComboBox"
  items="{modelExample>/}"
  selectionFinish=".onSelectionFinish">
  <core:ListItem text="{modelExample>Option}" />
</MultiComboBox>
let modelExample = {
  0: { "Option": "ExampleOption1" },
  1: { "Option": "ExampleOption2" }
};

One approach:

onSelectionFinish: function(oEvent){
  let aSelectedCriteria = [];
  let i = 0;
  while (i < oEvent.getSource().getSelectedItems().length) {
    aSelectedCriteria.push(oEvent.getSource().getSelectedItems()[i].getText())
    i = i + 1;
  }
},

Question: How to get the selected Items as Text from the list?

Upvotes: 1

Views: 2440

Answers (1)

Voyager
Voyager

Reputation: 840

My recommendation: Use the Array.prototype.map method to create an array of all texts. This is simply your approach with a more convenient method.

onSelectionFinish: function(oEvent) {
  const aSelectedItems = oEvent.getParameter("selectedItems");
  const aSelectedTexts = aSelectedItems.map(oItem => oItem.getText());
},

Another approach would be to only get the selected keys and then loop over your model instead.

onSelectionFinish: function(oEvent) {
  // There are multiple ways to retrieve your model
  const oModel = oEvent.getSource().getBinding("items").getModel();
  const aSelectedKeys = oEvent.getSource().getSelectedKeys();
  const aSelectedCriteria = aSelectedKeys.map(sKey => oModel.getProperty("/" + sKey);
},

Upvotes: 3

Related Questions