user851110
user851110

Reputation: 259

How map multiple inputText to an array or collection property?

I want the user to enter one or more names to the JSF's inputText components. So I'm thinking of a managed bean like this:

public class MyBean {

    private String[] names;

    public String[] getNames() {
        return names;
    }

    public void setNames(String[] names) {
        this.names = names;
    }
}

But, how do I map the JSF's inputText components to this array property?

Upvotes: 13

Views: 11560

Answers (2)

BalusC
BalusC

Reputation: 1108722

First, you need to ensure that the array or collection is preinitialized in the bean, i.e. that it is never null, for the simple reason because JSF won't do that for you as it doesn't know beforehand how many items you want.

E.g. in @PostConstruct.

@PostConstruct
public void init() {
    names = new String[3];
}

Then, you can either just access them by an hardcoded index

<h:inputText value="#{myBean.names[0]}" />
<h:inputText value="#{myBean.names[1]}" />
<h:inputText value="#{myBean.names[2]}" />

or use <ui:repeat> with a varStatus to access them by a dynamic index

<ui:repeat value="#{myBean.names}" varStatus="loop">
    <h:inputText value="#{myBean.names[loop.index]}" />
</ui:repeat>

Do not use the var attribute like

<ui:repeat value="#{myBean.names}" var="name">
    <h:inputText value="#{name}" />
</ui:repeat>

It won't work when you submit the form, because the immutable String class literally doesn't have a setter for the value (the getter is basically the toString() method implied by EL).

See also:

Upvotes: 14

Elidio Marquina
Elidio Marquina

Reputation: 121

This how i use using the upper example.

<c:forEach items="#{cotBean.form.conductor}" varStatus="numReg">
    <ice:panelGroup>
        <ice:selectOneMenu value="#{cotBean.form.conductor[numReg.index].gender}">
        </ice:selectOneMenu>
    </ice:panelGroup>
    <ice:panelGroup>
        <ice:selectOneMenu value="#{cotBean.form.conductor[numReg.index].dob.day}">
        </ice:selectOneMenu>
        <ice:selectOneMenu value="#{cotBean.form.conductor[numReg.index].dob.month}">
        </ice:selectOneMenu>
        <ice:selectOneMenu value="#{cotBean.form.conductor[numReg.index].dob.year}">
        </ice:selectOneMenu>
    </ice:panelGroup>
</c:forEach>

Upvotes: 2

Related Questions