2

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Eric
  • 1,171
  • 2
  • 14
  • 27

1 Answers1

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555