如何动态添加JSF组件

ErV*_*VeY 29 jsf dynamic-forms jsf-2

我可以动态添加JSF组件吗?我需要一个带有按钮的表单,该按钮应该<h:inputText>在表单中添加一个.这可能吗?

我知道这应该可以在JavaScript中以某种方式实现.有人知道如何在JSF中这样做吗?我认为主要的问题是如何通过获取或设置新输入的值#{value}.

Bal*_*usC 34

使用迭代组件,如<h:dataTable><ui:repeat>显示动态大小List的实体.使bean @ViewScoped确保在同一视图上的回发中记住列表,而不是一遍又一遍地重新创建.

开球示例<h:dataTable>:

<h:form>
    <h:dataTable value="#{bean.items}" var="item">
        <h:column><h:inputText value="#{item.value}" /></h:column>
        <h:column><h:commandButton value="remove" action="#{bean.remove(item)}" /></h:column>
    </h:dataTable>
    <h:commandButton value="add" action="#{bean.add}" />
    <h:commandButton value="save" action="#{bean.save}" />
</h:form>
Run Code Online (Sandbox Code Playgroud)

管理豆:

@ManagedBean
@ViewScoped
public class Bean {

    private List<Item> items;

    @PostConstruct
    public void init() {
        items = new ArrayList<Item>();
    }

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

    public void remove(Item item) {
        items.remove(item);
    }

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

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

}
Run Code Online (Sandbox Code Playgroud)

模型:

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

也可以看看:

  • 真正.唯一的选择是以编程方式创建组件,如`new HtmlInputText()`等等,但这只会导致托管bean中令人讨厌且不透明的代码. (5认同)