开发者

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

开发者 https://www.devze.com 2023-02-10 03:01 出处:网络
I have a bean with a List<T>: @Named @ViewScoped public class Bean { private List<Item> items;

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开发者_如何学Go.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?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号