Adding additional components to a web page after rendering by Wicket
-
07-07-2021 - |
Pergunta
I have a requirement to create a web page using Wicket 1.5, which can present a variable number of panels to capture user input. All the panels have the same structure. The page would start off with one panel, and includes a button to dynamically add more as required.
So the number of panels is unknown at the time the page is initially rendered. Effectively I'd be altering the structure of the page dynamically. This is possible in Javascript, using document.addElement()
I've done a similar thing in the past by creating all the components on page load, and selectively showing/hiding components.
The difference here is that the number of components (panels) is initially unknown. I'm unsure as to how this would be achieved with Wicket.
Solução
This is actually a common use case and is usually done with a RepeatingView (a ListView would repaint all your panels which is probably not what you want).
final RepeatingView rv = new RepeatingView("rv");
rv.add(new MyPanel(rv.newChildId()));
...
AjaxLink addPanelLink = new AjaxLink("addPanelLink") {
public void onSubmit(AjaxRequestTarget target) {
MyOtherPanel pnl = new MyOtherPanel(rv.newChildId())
rv.add(pnl);
target.prependJavaScript(String.format(
"var item=document.createElement('%s');item.id='%s';var container = $('%s'); container.append(item,container.firstChild);",
"div",
pnl.getMarkupId(),
".dom_parent_div_id"));
target.add(pnl);
}
};
Outras dicas
Use:
ListView
component to hold the panel.IndicatingAjaxSubmitLink
to add model objects to yourListView
model.
Whenever you add an object, simply refresh the webmarkupcontainer
holding the listview via Ajax.