Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring select multiple tag and binding

I am trying to use the select tag of spring to select multiple options to fill a List. My select tags is well displayed and when I select options the List is correctly updated.

The only problem I have is when I render the for with an already filled List, my select tag does not highlight the selected options. I have try to debug and Ican see that the List is not empty, it is really the tag that seems to not mark the selected options as selected.

My code :

@Entity
public class ProductsGroup
{
    @Version  @Column(name = "version")
    private Integer version;
    @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id")
    private Integer id;

    @ManyToMany(fetch = FetchType.EAGER)
    private List<Product> products; 

    public List<Product> getProducts()
    {
        return products;
    }

    public void setProducts(List<Product> products)
    {
        this.products = products;
    }
}

@Entity
public class Product
{
    @Version @Column(name = "version")
    private Integer version;

    @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id")
    private Long id;

    private String name;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}

<form:form action="${action}" class="fancyform" commandName="productsGroup" id="productForm">
    ....
    <form:select path="products" items="${products}" itemLabel="name" itemValue="id" multiple="true"/>
    ....
</form:form>
like image 713
tibo Avatar asked May 28 '12 01:05

tibo


1 Answers

It's probably due to the fact that the list of selected products doesn't contain the same instances as the complete list of displayed products.

The tag compares products with equals(), and you have not overridden equals() (and hashCode()) in your Product class.

So even if the selected products contain the Product with the name "foo", and the complete list of Product also contains a Product with the name "foo", those products are not equal, and Spring thus doesn't know they're the same product, and that this product should thus be selected.

like image 84
JB Nizet Avatar answered Sep 23 '22 22:09

JB Nizet