Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use <form:select> tag with a map

Is there a way to map the data inside a map to tag? I have a map Map<String, Integer> in my code. Is there a way to map the option labels to the String in the map and the Integer to the option values?

like image 258
Batman Avatar asked Feb 09 '12 12:02

Batman


2 Answers

The <form:options> tag supports what you want right out of the box, using the items attribute. You can do something like this:

LinkedHashMap<Integer, String> states = new LinkedHashMap<Integer, String>();
states.put(1, "Alabama");
states.put(2, "Alaska");
states.put(3, "Arizona");
states.put(4, "Arkansas");
states.put(5, "California");

And so on. Then in your form:

<form:select path="state">
    <form:options items="${states}" />
</form:select>

That will be rendered to something like:

<select name="state">
    <option value="1">Alabama</option>
    <option value="2">Alaska</option>
    <option value="3">Arizona</option>
    <option value="4">Arkansas</option>
    <option value="5">California</option>
</select>
like image 147
The Awnry Bear Avatar answered Oct 06 '22 00:10

The Awnry Bear


See the Spring form:select and form:options documentation. Use items, itemValue, and itemLabel as needed.

<form:select path="myFormVariable">
    <form:option value="0" label="Select One" />
    <form:options items="${myCollection}" itemValue="propertyToUseAsValue" itemLabel="propertyToUseAsDisplay" />
</form:select>
like image 22
Snowy Coder Girl Avatar answered Oct 06 '22 01:10

Snowy Coder Girl