How to collect submitted values of a List<T> in JSF?

2.9k views Asked by At

I have a bean with a List<T>:

@Named
@ViewScoped
public class Bean {

    private List<Item> items;
    private String value;

    @Inject
    private ItemService itemService;

    @PostConstruct
    public void init() {
        items = itemService.list();
    }

    public void submit() {
        System.out.println("Submitted value: " + value);
    }

    public List<Item> getItems() {
        return items;
    }
}

And I'd like to edit the value property of every item:

<h:form>
    <ui:repeat value="#{bean.items}" var="item">
        <h:inputText value="#{bean.value}" />
    </ui:repeat>
    <h:commandButton action="#{bean.submit}" />
</h:form>

With this code the value doesn't contain all the submitted values, only the latest submitted value. I also tried <c:forEach> and <h:dataTable>, but it didn't made any difference.

What should I do for collecting all the submitted values?

1

There are 1 answers

0
BalusC On

Your problem is caused because you're basically collecting all submitted values into one and same bean property. You need to move the value property into the bean behind var="item".

<h:form>
    <ui:repeat value="#{bean.items}" var="item">
        <h:inputText value="#{item.value}" /> <!-- instead of #{bean.value} -->
    </ui:repeat>
    <h:commandButton action="#{bean.submit}" />
</h:form>

In the bean action method, simply iterate over items in order to get all submitted values via item.getValue().

public void submit() {
    for (Item item : items) {
        System.out.println("Submitted value: " + item.getValue());
    }
}