Search code examples
jsfjsf-2facelets

How do I generate a number of text boxes depending on a stored value?


I need to create a number of input boxes depending on a value in a backing bean. If the product allows 5 users I need 5 sets of input fields.

The number of input boxes is known when I load the page.

Any ideas? This one has had me stumped for a while now.


Solution

  • Let the bean prepare a List<Item> based on the number.

    @ManagedBean
    @ViewScoped
    public class Bean {
    
        private int count;
        private List<Item> items;
    
        public Bean() {
            count = 5;
            items = new ArrayList<Item>();
    
            for (int i = 0; i < count; i++) {
                items.add(new Item());
            }
        }
    
        public void submit() {
            System.out.println(items);
        }
    
        public List<Item> getItems() {
            return items;
        }
    
    }
    

    Where the Item is just a simple Javabean with a value property.

    Let the view iterate over it using <ui:repeat> or <h:dataTable>.

    <h:form>
        <ui:repeat value="#{bean.items}" var="item">
            <h:inputText value="#{item.value}" /><br />
        </ui:repeat>
    
        <h:commandButton value="Submit" action="#{bean.submit}" />
    </h:form>