fliim
fliim

Reputation: 2189

Select multiple of enum list

How can I bind a list of enum in a multiple select ?

here is my class property (with the getter/setter):

private List<Color> colors;

And here is my jsp:

<form:select id="colors" path="colors" multiple="true">
  <form:option value="" label="..."/>
  <form:options items="${Color.values}" />
</form:select>

I couldnt get the enum values as array, because its empty.

Thanks for reading.

Upvotes: 5

Views: 2924

Answers (2)

Sam Nunnally
Sam Nunnally

Reputation: 2321

Try something like this to get the enums as a List:

List<Color> colors = Arrays.asList(Color.values());

For a given enum:

    public enum Color {
        blue,
        red;
    }

Or have your getter return the array or List immediately:

    public Color[] getColors(){
        return Color.values();
    }

List

    public List<Color> getColorList(){
        return Arrays.asList(Color.values());
    }

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691685

You seem to think that ${Color.values} will call the static Color.values() method. That is incorrect.

Before Java EE 7 (Tomcat 8), there's no support for static methods in the JSP EL. ${Color.values} will search for an attribute named Color, and, if found, call getValues() on this object. Since there is no such object in any scope, you won't have any option in your select box.

To do what you want, simply call Color.values() from your Spring controller and add it to the model, for example, under the allColors attribute name. Then use

<form:options items="${allColors}" />

in your JSP

If you're using Java EE 7, then you can import the Color class in your JSP, and use ${Color.values()}.

Upvotes: 6

Related Questions