开发者

How to save a list/map/set in JSF with h:inputText + managed bean

What I'm trying to achieve is very similar to the one posted in the following link.

How to save an array in JSF with ui:repeat + h:inputText + managed bean?

I'm particularly fascinated with the answer provided by Arjan Tijms in the link above however what I want to achieve is slightly different. Consider the following code snippets.

The bean

import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;

@RequestScoped
@Named
public class MyBean {

    List<String> choices;

    public List<String> getChoices() {
        return choices;
    }

    @PostConstruct
    public void initChoices() {
        choices= new ArrayList<String>();
    }

    public Str开发者_如何学Pythoning save() {
        // should save all the choices into some repository
        return "";
    }
}

and the facelet page

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"        
    xmlns:ui="http://java.sun.com/jsf/facelets">

    <h:body>

        <h:form>
            <ui:repeat value="#{myBean.choices}" varStatus="status">            
                <h:inputText value="#{myBean.choices[status.index]}" />
            </ui:repeat>
            <h:commandButton value="Save" action="#{myBean.save}" />
        </h:form>
    </h:body>
</html>

The thing is, this will work if we have some initial data in the list at the beginning. What about situations where the initial list will be empty?

The ideal solution which I'm looking for is to have 1 h:inputText for each choice and when save button is clicked, all choices in each h:inputText is then added to the choices list. I've searched high and low but can't seem to find any hints on how this can be done.

If JSF 2 really doesn't support this, I guess I'll have to use the ugly way with just one h:inputText and use a converter to convert to and from a list but I'm still hoping that an ideal solution can be found.

Hopefully someone from stackoverflow can shed a light in the right direction for me.


Just add an "add" button which adds a new String to the list.

<ui:repeat value="#{myBean.choices}" varStatus="status">            
    <h:inputText value="#{myBean.choices[status.index]}" />
</ui:repeat>
<h:inputText value="#{myBean.newChoice}" />
<h:commandButton value="Add" action="#{myBean.add}" />
<h:commandButton value="Save" action="#{myBean.save}" />

with

private String newChoice;

public void add() {
    choices.add(newChoice);
    newChoice = null;
}

// ...

Note that this only works if bean is put in view scope. A request scoped one would be constructed on every request and hereby recreate the list everytime.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜