Search code examples
sapui5

UI5 - how to dynamically bind data to a Select in Table, depending on another combobox?


I have a classic situation - a table with two comboboxes (or, to be exact, sap.m.Select controls) and after select in the first one, I would like to have the values in the second one updated. This is my model, basically, the first combobox should contain the list of available states and once some is selected, the second sap.m.Select control should be populated by relevant cities

{
 countries: [
 { country: 'France', cities: ['Paris', 'Marseille', 'Lyon']},
 { country: 'Germany', cities: ['Berlin', 'Bonn']}
]
}

The problem is that I dont know how to do it. I am able to get the id of the updated row using something like this.

onCountryChange: function (oEvent) {
    const selectedItem = oEvent.getParameter("selectedItem");
    var path = selectedItem.getBindingContext().getPath();
    bindComboBox(path); // this should rebind the data, but not written yet
}

I know now I should rebind the data in the correct combobox, however, I don't know how to affect only that single combobox on the correct row and how to update it. Could someone advise me how to do it? The whole table is defined in the .xml view, can I do it also with a formatter or inline expression or is this scenario too difficult for that?

Thank you


Solution

  • You can use the bindAggregation method (from the ManagedObject) class to rebind the combo boxes' items.

    onCountryChange: function (oEvent) {
        const selectedItem = oEvent.getParameter("selectedItem");
        var path = selectedItem.getBindingContext().getPath();
    
        this.byId("combo2").bindAggregation("items", {
            path: path + "/cities",
            template: new sap.ui.core.Item({
                key: "{}",
                text: "{}"
            })
        });
    }
    

    Note: Replacing "combo2" with the id of your 2nd combo box/select control.

    Edit: To get the correct combo box (assuming you have multiple created on a table, use the ID of the first combo box (oEvent.getSource().getId()) to generate the ID of the 2nd combo box. Without knowing more of the structure of the table (and how it's created) I can't offer more.