How to get the value of an input component in the same datatable row as the button?

前端 未结 1 1064
时光说笑
时光说笑 2021-01-15 23:05

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

相关标签:
1条回答
  • 2021-01-15 23:23

    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();
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题