Question
Answer and Explanation
To get selected rows from a UI5 table, you can use the getSelectedContexts()
method of the table. This method returns an array of binding contexts representing the selected rows. Here's how you can achieve this:
1. Get a Reference to the UI5 Table:
First, you need to obtain a reference to the sap.ui.table.Table
control. You can do this using its ID with sap.ui.getCore().byId()
or, if you're within a View or Fragment, using this.getView().byId()
.
2. Retrieve Selected Contexts:
Call the getSelectedContexts()
method on the table instance. This method returns an array of sap.ui.model.Context
objects, each representing a selected row.
3. Extract Row Data:
Iterate through the array of contexts and use the getObject()
method of each context to retrieve the actual data object representing the selected row.
4. Example Code:
function getSelectedTableRows() {
const table = sap.ui.getCore().byId("yourTableId"); // Replace "yourTableId" with your table's ID
if (!table) {
console.error("Table not found");
return;
}
const selectedContexts = table.getSelectedContexts();
const selectedRowsData = selectedContexts.map(context => context.getObject());
console.log("Selected Rows Data:", selectedRowsData);
//You can now use the selectedRowsData array
}
5. Important Considerations:
- Ensure that you have a table with a selection mode that allows row selection (e.g., SingleSelect, MultiSelect).
- Check if there are any selected rows before proceeding, by checking the length of the array returned by getSelectedContexts()
.
- The data objects returned by getObject()
will have properties that correspond to the columns of your table, depending on how you have bound the data to the table.
This approach provides a straightforward way to access the data associated with the selected rows in your UI5 table, enabling you to implement features that depend on selected data.