问题
I have a screen with inputText, beside it there's a (+) button, when the user should press that button the form should add another extra inputText beside it (or below, whatever)
Here's the code:
<table>
<tr>
<td>
<p:inputText value="#{controller.x}" />
<img src="../images/ico_plus.png" />
</td>
</tr>
</table>
in Controller.java:
private String x;
public String getX(){return x}
public void setX(String val){x = val}
I need the page to be populated with multiple fields and the controller to have all the fields values' fetched
回答1:
This question was answered more than one time, basically you need to keep a List for all fields in the bean, and you remove or add to this List with your buttons. Note this is important to be in ViewScoped or SessionScoped ortherwise your List will be reset at every actions.
View :
<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>
Helper class :
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;
}
}
Bean :
@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());
}
}
来源:https://stackoverflow.com/questions/16761441/dynamic-adding-text-fields-in-jsf