31

There is a select dropdown and I want to add "No selection" item to the list which should give me 'null' when submitted. I'm using SimpleFormController derived controller.

protected Map referenceData(HttpServletRequest httpServletRequest, Object o, Errors errors) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();

    map.put("countryList", Arrays.asList(Country.values()));

    return map;
}

And the jspx part is

<form:select path="country" items="${countryList}" title="country"/>

One possible solution seems to be in adding a null value to the beginning of the list and then using a custom PropertyEditor to display this 'null' as 'No selection'. Is there a better solution?

@Edit: I have solved this with a custom validation annotation which checks if the selected value is "No Selection". Is there a more standard and easier solution?

2 Answers 2

41

One option:

<form:select path="country" title="country" >
     <form:option value="">&nbsp;</form:option>
     <form:options items="${countryList}" />
</form:select>
2
  • Watch out with using the named entity &nbsp; in jspx pages (it's recently lead to errors for me, stating that the entity is not defined, or some such). It seems safer to refer to the non-breaking space by it's code: &#160;
    – Michael
    Commented Apr 22, 2015 at 8:08
  • 1
    In this way NoSelection will post an empty string, not 'null', though. value=${null} should post null.
    – javabot
    Commented May 11, 2015 at 13:25
1

I don't think you should need a property editor for this. If the "blank" option is first in the list, and the tag that outputs the list doesn't mark any of them as selected, then the browser should select the first, "blank" one automatically.

When you submit the form, try and work it so that the "blank" value is bound to your command as a null, which might happen automatically, depending on the type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.