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

爱⌒轻易说出口 提交于 2020-05-23 17:33:43

问题


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:


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


来源:https://stackoverflow.com/questions/4951421/how-to-collect-submitted-values-of-a-listt-in-jsf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!