我会在组合组件中使用
<h:dataTable>
,并使用
<composite:interface>
的
componentType
属性绑定支持的
UIComponent
。然后,在支持的
UIComponent
中,您可以维护
DataModel
并定义操作。
dynamicFieldList.xhtml
<ui:composition
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:cc="http://java.sun.com/jsf/composite"
>
<cc:interface componentType="dynamicFieldList">
<cc:attribute name="value" type="java.util.List" required="true" />
</cc:interface>
<cc:implementation>
<h:dataTable id="table" binding="#{cc.table}" value="#{cc.attrs.value}" var="field">
<h:column><h:outputLabel value="#{field.label}" /></h:column>
<h:column><h:inputText value="#{field.value}" /></h:column>
<h:column><h:commandButton value="remove" action="#{cc.remove}" /></h:column>
</h:dataTable>
<h:commandButton value="add" action="#{cc.add}" />
</cc:implementation>
</ui:composition>
(如果需要,<h:inputText>
可以是您的组合字段组件)
com.example.DynamicFieldList
(注:本文为IT技术相关内容)
@FacesComponent(value="dynamicFieldList")
@SuppressWarnings({"rawtypes", "unchecked"})
public class DynamicFieldList extends UINamingContainer {
private UIData table;
public void add() {
((List) getAttributes().get("value")).add(new Field("somelabel"));
}
public void remove() {
((List) getAttributes().get("value")).remove(table.getRowData());
}
public UIData getTable() {
return table;
}
public void setTable(UIData table) {
this.table = table;
}
}
使用方法如下:
<h:form>
<my:dynamicFieldList value="#{bean.fields}" />
</h:form>
仅使用此功能
@ManagedBean
@ViewScoped
public class Bean implements Serializable {
private List<Field> fields;
public Bean() {
fields = new ArrayList<>();
}
public List<Field> getFields() {
return fields;
}
}
并且
public class Field implements Serializable {
private String label;
private String value;
public Field() {
}
public Field(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
UIComponent
”,在其中定义操作。 - BalusC