Search code examples
javaobjectwicketdropdownchoice

Wicket DropDownChoice saves object to database, instead of field


I have a problem implementing dropdownchoice in my code. I want to display a list of object of type ProductCategory. This is all well and fine, but when i try to save the form, the whole ProductCategory object is saved, and not just the field from the object which is displayed in the select list.

Here is what my code looks like:

    IModel categories = new LoadableDetachableModel() {
        public List<ProductCategory> load() {
            List<ProductCategory> l = categoryService.findAllProducts();
            return l;
        }
    };

    IChoiceRenderer renderer = new IChoiceRenderer() {
        public Object getDisplayValue(Object obj) {
            ProductCategory category = (ProductCategory) obj;
            return category.getName();
        }

        public String getIdValue(Object obj, int index) {
            ProductCategory category = (ProductCategory) obj;
            return category.getName();
        }
    };

    DropDownChoice<ProductCategory> listCategories = new DropDownChoice<ProductCategory>(
            "productCategory",
            categories,
            renderer
    );

    add(listCategories);

The generated HTML looks something like this:

<select wicket:id="productCategory" name="productCategory">
    <option selected="selected" value="">Vælg en</option>
    <option value="test1">test1</option>
    <option value="test2">test2</option>
</select>

The "productCategory" field exists in an Object of type "Product", and is of type String.

As i tried to describe; i want to save ProductCategory.getName() to the "productCategory" field in Product, and not the entire ProductCategory Object. In other words: I want to save "test1" to Product.productCategory, but instead it saves com.test.webapp.domain.ProductCategory@1.

Can anyone please tell how this is done?

Any help is much appreciated.


Solution

  • Your problem is that the model object behind the ddc is of type ProductCategory. On save, this will be casted to the String type - as defined in your model object behind the form.

    I would change the code to have only strings in your choice list.

        public List<String> load() {
            List<String> pcChoices = new ArrayList<String>();
            for(ProductCategory pc : categoryService.findAllProducts()) {
                pcChoices.add(pc.getName());
            }
            return pcChoices;
        }
    

    Doing so, you can also get rid of your choice renderer.