I am trying to create dynamic input textfields with labels using primefaces.
Like if I click the add button it should keep adding a label and a input textfields.
What component I can use ? thanks.
Asked
Active
Viewed 1,915 times
2
1 Answers
5
You can use a <h:dataTable>
in combination with a @ViewScoped
bean for this.
E.g.
<h:form>
<h:dataTable id="inputs" value="#{bean.inputs}" var="input">
<h:column>
<p:outputLabel for="input" value="#{input.label}" />
</h:column>
<h:column>
<p:inputText id="input" value="#{input.value}" />
</h:column>
</h:dataTable>
<p:commandButton value="Add" action="#{bean.add}" update="inputs" />
</h:form>
with
@ManagedBean
@ViewScoped
public class Bean implements Serializable {
private List<Input> inputs;
@PostConstruct
public void init() {
inputs = new ArrayList<Input>();
}
public void add() {
Input input = new Input();
input.setLabel("Input " + (inputs.size() + 1));
inputs.add(input);
}
public List<Input> getInputs() {
return inputs;
}
}
and
public class Input {
private String label;
private String value;
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;
}
}
You can of course also use a <p:dataTable>
, but that would only add some fancy look'n'feel which is likely unnecessary for this particular use case.
See also:
-
I didnt know that we can use inputtextfields inside datatable. thank you very much. – Eric Aug 09 '12 at 13:16
-
I will try to use collector as well, and will see which one suit better – Eric Aug 09 '12 at 13:18
-
@BalusC How we can add remove functionality for added items? – mabuzer Sep 25 '12 at 08:44
-
@mabuzer: this is shown in the example behind the "see also" link. – BalusC Sep 25 '12 at 10:54