I am trying to make a input form for answers in my application and I start with four "empty" answers which the view loops over and make input fields for. I have an add answer button which I add one question to the array of answers and then the view render the answers again, but now with an additional input field. The backing bean is viewscoped. However if I submit the form without pressing the add answer button it all works. The data is saved in the database. But if I add an answer after the four is filled out the last one does not get the data from the inputfield (answer.description). If I press the add answer first (without filling out any input fields) the data from the fields are not captured at all leaving all 5 empty so no data is saved in the database.
I have this in the form:
<ui:repeat var="answer" value="#{bean.answers}">
<div class="field">
<h:outputLabel for="answerAlternative-#{answer.serialNumber}"
value="Svaralternativ #{answer.serialNumber}" />
<h:inputText id="answerAlternative-#{answer.serialNumber}"
value="#{answer.description}" size="40" />
</div>
</ui:repeat>
This is the method for creating a new input field:
public String addAnswer() {
if (answers.size() + 1 < 6) {
Answer answer = new Answer();
answer.setSerialNumber(answerSerialNumber + "");
answerSerialNumber++;
answers.add(answer);
}
return null;
}
Used for initializing the answers array with four empty input fields:
@PostConstruct
public void initBean() {
answers = new ArrayList<Answer>();
for (int i = 0; i < 4; i++) {
addAnswer();
}
}