这个问题被回答了不止一次,基本上你需要为 bean 中的所有字段保留一个,然后用你的按钮List
删除或添加它。List
请注意,这很重要,ViewScoped
否则SessionScoped
您List
将在每次操作时重置。
看法 :
<h:form>
<h:dataTable id="tblFields" value="#{bean.fields}" var="field">
<h:column>
<h:inputText value="#{field.value}" />
</h:column>
<h:column>
<h:commandButton value="Remove">
<f:ajax listener="#{bean.onButtonRemoveFieldClick(field)}" immediate="true" render="@form" />
</h:commandButton>
</h:column>
</h:dataTable>
<h:commandButton value="Add">
<f:ajax listener="#{bean.onButtonAddFieldClick}" execute="@form" render="tblFields" />
</h:commandButton>
</h:form>
助手类:
public class Field implements Serializable
{
private String m_sName;
public void setName(String p_sName)
{
m_sName = p_sName;
}
public String getName()
{
return m_sName;
}
}
豆 :
@ManagedBean
@ViewScoped
public class Bean implements Serializable
{
private List<Field> m_lFields;
public Bean()
{
m_lFields = new ArrayList();
m_lFields.add(new Field());
}
public void setFields(List<Field> p_lFields)
{
m_lFields = p_lFields;
}
public List<Field> getFields()
{
return m_lFields;
}
public void onButtonRemoveFieldClick(final Field p_oField)
{
m_lFields.remove(p_oField);
}
public void onButtonAddFieldClick(AjaxBehaviorEvent p_oEvent)
{
m_lFields.add(new Field());
}
}