Skip to content

Wicket dynamically add components to form

I’m having trouble adding components to a form dynamically. What I’m trying to do is: Give the user a drop-down list with items they can choose like name, age, …

When a user presses add: there comes a (label + inputbox) in 1 component which allows them to put in the value. You might think I could hide those components which aren’t selected but the user is also able to add values to the drop-down list.

The problem I have is how to add and remove components (label+ inputbox) without having wicket:ids in the HTML?

This is what I’m trying to add:

<wicket:panel>
  <div wicket:id="hldValue">
    <label wicket:id="lblValue"></label>
    <input type="text" wicket:id="value"/>
  </div>
</wicket:panel>

The problem I have here is that the ID is always the value I want to name dynamically. Is using dynamic HTML to create this component a good idea? I’m overriding getMarkupResourceStream and getCacheKey to achieve this. Still I feel this is not the right way. Any other suggestions?

Answer

You need a ListView because you can n have type of panels , a model where you add the logic with the listview, at least 2 forms , one for the DropDown where the user select the data too add and finally another to submit the data for entire ListView. You could use AJAX but is optional

in order to know how to use repeaters(the ListView is a advanced repeater) with form components you can check here to know his basic usage, here for his usage with form components and finally here to know how to use it with AJAX.

BTW i have a example, here is just the critical part of the code.

this is populateItem method on ListView.class

 @Override
 protected void populateItem(ListItem<ListViewModel> item) {     
     item.add(new TextField<Integer>("quantity", new PropertyModel<Integer>(item.getDefaultModelObject(),
     "averageQuantity"));
     item.add(new TextField<Integer>("position", new PropertyModel<Integer>(item.getDefaultModelObject(), "order"))
     .add(new IntegerValidator()));
     item.add(new Label("description", item.getModelObject().getName()));
     item.setOutputMarkupId(true);
 }

in other place you should add the dropdown to his own form and then on submit manipulate the listView object for example

 // I use a AjaxButton to perform the user submit if you don't 
 // want use it, you should reload the entire page
 @Override
 protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
     //redraw the parent of the list view 
     target.add(theContainerOfTheListView);
     //the submited model of the dropdown
     ListViewModel item = form.getObject();                
     List<ListViewModel> list = listViewObject.getObject();
     list.add(item);
     //you could sort the list object in order to sort the listViewObject
 }

UPDATE: before add the new item to the listview you should submit the form components of the list view, if you donĀ“t do it you going to loose the user changes