La Chamelle
La Chamelle

Reputation: 2967

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

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?

Upvotes: 4

Views: 2934

Answers (1)

BalusC
BalusC

Reputation: 1108632

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());
    }
}

Upvotes: 3

Related Questions