Search code examples
wicketdropdownchoice

Wicket - DropDownChoice with object Selected


Im having problem with a DropDownChoice. I have to pre-selected an item but every tutorial and example I have found, only consider a list of primitive type.

I have a list of Object.

class myObject {
   private String name;
   private String surname;
   [setter and getter]
} 

In other class

List<MyObject> myList = some_data_retrieve();
MyObject defaultValue = some_simple_data_retrieve();

To build the DropDownChoice im using the following constuctor:

final DropDownChoice<T> ddc = new DropDownChoice<T>(id, data, new ChoiceRenderer<T>(choiceRendererExpression, choiceRendererIdExpression));

In this way:

final DropDownChoice<myObject> ddc = new DropDownChoice<myObject>("wicket_id", myList, new ChoiceRenderer<myObject>("name", "surname"));

Now. In every tutorial/example they use another constructor with a Model. For example:

private static final List<String> SEARCH_ENGINES = Arrays.asList(new String[] {
        "Google", "Bing", "Baidu" });
private String selected = "Google";
DropDownChoice<String> listSites = new DropDownChoice<String>(
        "sites", new PropertyModel<String>(this, "selected"), SEARCH_ENGINES);

I have tried something like this to emulate that kind of call:

final DropDownChoice<myObject> ddc = new DropDownChoice<myObject>("wicket_id", new PropertyModel<myObject>(this,"defaultValue"),myList, new ChoiceRenderer<myObject>("name", "surname"));

But what I got is an error:

No get method defined for class: package$WicketPage expression: defaultValue

Please, help me undersand.

Thanks


Solution

  • This means that you need to add a getter and setter of your "defaultValue" in the page or component where you are adding the DropDownChoice.

    public class MyPage extends WebPage {
    
        private MyObject defaultValue;
    
        public MyPage(PageParameters pageParameters) {
            super(pageParameters);
    
            defaultValue = some_simple_data_retrieve();
            List<MyObject> myList = some_data_retrieve();
    
            add(new DropDownChoice<myObject>(
                           "wicket_id",
                           new PropertyModel<MyObject>(this,"defaultValue"),
                           myList, 
                           new ChoiceRenderer<MyObject>("name", "surname")
            );           
        }
    
        public MyObject getDefaultValue() {
            return defaultValue;
        }
    
        public void setDefaultValue(MyObject defaultValue) {
            this.defaultValue = defaultValue;
        }
    }