1

I have a datatable where the rows are dynamic and each row contain a selectOneMenu. If I have a button on each row and I want to get the selected item on the selectOneMenu, what's the best way to do it?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Ikthiander
  • 3,917
  • 8
  • 37
  • 54

1 Answers1

4

Wrap the collection behind datatable's value in a DataModel<E>.

private List<Item> items;
private DataModel<Item> model;  // +getter

@PostConstruct
public void init() {
    this.items = loadItSomehow();
    this.model = new ListDataModel<Item>(items);
}

(the Item in this example is just the javabean class representing every row, e.g. Person, Product, etc)

Bind it to the datatable's value instead.

<h:dataTable value="#{bean.model}" var="item">

If the dropdown is bound to a property of Item and the button to a method of the same bean ...

<h:column>
    <h:selectOneMenu value="#{item.value}">
        <f:selectItems value="#{bean.values}" />
    </h:selectOneMenu>
</h:column>
<h:column>
    <h:commandButton value="submit" action="#{bean.submit}" />
</h:column>

... then you can grab the current item by DataModel#getRowData() and corrspondingly also the selected value in action method as follows:

public void submit() {
    Item item = model.getRowData();
    String value = item.getValue();
    // ...
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555