Search code examples
jsfjsf-2

Passing form input values as a List of objects from a JSF page


For instance if I have a Model with two properties as below

 public class Model{
         private name;
         private email;

        //constructor
        //getters and setters
       }

then I have a backing bean in which i there is a List of Model instance

  Bean {

    List<Model> models = new ArrayList<>();

}

     //getters and setters

now my headache here will be how to put each set of form values as Objects into the list,if in a single form I have repeated sets of components pointing to the backing bean.

For instance if I have a JSF page that looks like this

<h:form>
//firstset
<h:inputText value="#{bean.name}"/>
<h:inputText value="#{bean.email}"/>
//secondset
<h:inputText value="#{bean.name}"/>
<h:inputText value="#{bean.email}"/>
<h:form>

how do get the list to be populated this way:

 [Model{//first set values},Model{//second set values}]

Solution

  • Use <c:forEach>:

    <h:form>
        <c:forEach items="#{bean.models}" var="model">
            <h:inputText value="#{model.name}"/>
            <h:inputText value="#{model.email}"/>
        </c:forEach>
    <h:form>