views:

299

answers:

1

Can I add JSF components dynamically?

I know this should be possible in JavaScript somehow. Do anybody know how to do this in JSF? I think the major problem is how do I get or set values later via #{value}.

I need to have a form with a button which should add one h:inputText to the form. Is this possible?

+3  A: 

Use a h:dataTable to display a dynamically sized collection of items.

JSF kickoff example:

<h:form>
    <h:dataTable value="#{bean.items}" var="item">
        <h:column><h:inputText value="#{item.value}" /></h:column>
    </h:dataTable>
    <h:commandButton value="add" action="#{bean.add}" />
    <h:commandButton value="submit" action="#{bean.submit}" />
</h:form>

Bean class:

@ManagedBean
@ViewScoped
public class Bean {
    private List<Item> items = new ArrayList<Item>();

    public void add() {
        items.add(new Item());
    }

    public void submit() {
        System.out.println("items: " + items);
    }

    public List<Item> getItems() {
        return items;
    }
}

Item class:

public class Item {
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String toString() {
        return String.format("Item[value=%s]", value);
    }
}
BalusC
thanks, was thinking the same thing, only wondering if it was the best way to do it = D
ErVeY
True. The only alternative would be creating components programmatically like `new HtmlInputText()` and so on, but that would only result in nasty and opaque code in managed bean.
BalusC