本文介绍了如何动态添加JSF组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can I add JSF components dynamically? I need to have a form with a button which should add one <h:inputText> to the form. Is this possible?

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

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 of new inputs via #{value}.

推荐答案

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

Use an iterating component like <h:dataTable> or <ui:repeat> to display a dynamically sized List of entities. Make the bean @ViewScoped to ensure that the list is remembered across postbacks on the same view instead of recreated over and over.

使用<h:dataTable>的启动示例(使用<ui:repeat>时,只需将<h:dataTable>替换为<ui:repeat>,并将<h:column>替换为例如<li><div>):

Kickoff example with <h:dataTable> (when using <ui:repeat> simply replace <h:dataTable> by <ui:repeat>, and <h:column> by e.g. <li> or <div>):

<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>

托管bean:

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

}

型号:

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

}

另请参见:

07-28 06:05
查看更多