Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How map multiple inputText to an array property?

Tags:

jsf

jsf-2

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?

like image 679
user851110 Avatar asked Jul 19 '11 02:07

user851110


2 Answers

First, you need to preserve the array in bean's (post)constructor. E.g.

public MyBean() {
    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 String doesn't have a setter for the value (the getter is basically the toString() method).

like image 96
BalusC Avatar answered Nov 04 '22 06:11

BalusC


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>
like image 23
Elidio Marquina Avatar answered Nov 04 '22 07:11

Elidio Marquina