我正在製作一個表單,讓教師創建問題。一類問題是多選題。該表單有一個textArea,您可以在其中編寫問題表達式,以及一個帶替代方案textField的listView。Wicket:重新繪製文本框並保留用戶輸入
有一個按鈕來添加一個新的選擇(添加一個新的textField),當按下它重新繪製所有的替代品,並添加一個新的。現在問題是這樣的:我想讓列表視圖中已有的文本字段帶有文本,以便在重繪後保留教師寫的文本,但我不知道如何使這成爲可能(除了在每次重繪之前將值保存到數據庫,但這似乎是一個壞主意)。
這是我的MultipleChoiceQuestionPanel的代碼,我希望它已經足夠。
public class MultiChoiceQuestionPanel extends QuestionPanel {
private List<Alternative> alternatives;
@SpringBean
private AlternativeRepository alternativeRepository;
public List<Alternative> getAlternatives(){
return alternatives;
}
public MultiChoiceQuestionPanel(String id, MultipleChoiceQuestion q){
super(id, q);
final WebMarkupContainer parent = new WebMarkupContainer("alternativesContainer");
parent.setOutputMarkupId(true);
add(parent);
parent.add(new Label("AnswerLabel", "Svar"));
q.setAlternatives(alternativeRepository.findByMultipleChoiceQuestion(q));
alternatives = q.getAlternatives();
Form form = new Form("addForm");
form.add(new ListView<Alternative>("alternatives", alternatives) {
@Override
protected void populateItem(final ListItem<Alternative> alternativeListItem) {
alternativeListItem.add((TextField<String>) new TextField<String>("alternative", new AlternativeModel(alternativeListItem.getModelObject())).setRequired(true).setType(String.class));
Form form = new Form("removeForm");
form.add(new AjaxSubmitLink("remove") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
Alternative selected = alternativeListItem.getModelObject();
alternativeRepository.delete(selected);
getAlternatives().remove(selected);
target.addComponent(parent);
}
});
alternativeListItem.add(form);
add(alternativeListItem);
}
});
AjaxSubmitLink a = new AjaxSubmitLink("add") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
Alternative alternative = new Alternative();
MultipleChoiceQuestion mcq = (MultipleChoiceQuestion) getQuestion();
alternative.setSequenceNumber(mcq.getAlternatives().size());
alternative.setMultipleChoiceQuestion((MultipleChoiceQuestion) getQuestion());
alternativeRepository.save(alternative);
getAlternatives().add(alternative);
target.addComponent(parent);
}
};
a.setDefaultFormProcessing(false);
form.add(a);
parent.add(form);
}
}
任何幫助表示讚賞。
謝謝你,這解決了問題! –
@LeoSundholm不客氣。 – Nicktar
雖然這似乎創造了一個新問題。 添加新的textField完美地工作,但我的刪除按鈕現在行爲很奇怪。無論我按下哪個刪除按鈕,它都是最後一個textField的文本消失,而不是我刪除的textField中的文本。爲什麼會有任何解釋/建議? –