问题描述
我可以动态添加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);
}
}
另请参见:
- 推荐的JSF 2.0 CRUD框架
- 如何创建动态JSF表单字段
- 如何使用JSF 2.0复合组件实现动态列表?
- 如何选择正确的bean作用域?
- Recommended JSF 2.0 CRUD frameworks
- How to create dynamic JSF form fields
- How to implement a dynamic list with a JSF 2.0 Composite Component?
- How to choose the right bean scope?
See also:
这篇关于如何动态添加JSF组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!