Reputation: 501
I have an HTML form bound to a Spring model to take in user data and add it to a database. This works fine. I have used Spring Freemarker macros for the fields to take input and validate before sending, e.g.
<@spring.formInput path="myForm.username"/>
<@spring.showErrors ", "/>
This also works fine for text input. What is causing me problems is rendering multiple checkboxes with the Spring macro. My original HTML was:
<input name="roleList" type="checkbox" value="1"/>Adminstrator
<input name="roleList" type="checkbox" value="2"/>Developer
<input name="roleList" type="checkbox" value="3"/>Customer
I created a Java Map<String, String>
of this information with the keys as "1", "2", "3" in my controller method and added it to the model, then replaced the HTML with this macro in my ftl template:
<@spring.formCheckboxes path="quickForm.roleList" options="${roleMap}" separator="<br>"/>
But I get an error
Expecting a string, date or number here, Expression roleMap is instead a freemarker.template.SimpleHash
Why would it give that message if it requires a Map? (as in the Spring Docs for FreeMarker macros) Can anyone explain how I should be providing the checkbox data?
Upvotes: 1
Views: 7168
Reputation: 501
Finally worked this out, so for anyone who's interested: it wasn't as straightforward as just creating a HashMap of values and adding them with model.addAttribute("roleMap", myHash)
- I had to create a service class to do this instead: it retrieved my list of roles from a database table and then converted them into a HashMap<String, String>
. I then called this in my controller method, added it to my model (called "roleMap" here) and used it within my FreeMarker template without the usual formatting, like this:
<@spring.formCheckboxes path="quickForm.roleList" options=roleMap separator="<br>"/>
Having the data converted in a service method was key for Spring to use it as checkbox options.
Upvotes: 3