Default value of form object's field
I have a form where depending on the select state ([checkboxOn/checkboxOff]) a check box should appear or not. When the check box is displayed it should be checked by default.
How to handle that situation, taking into account that
- when select is in 'checkboxOff' state, I would have MyFormObject.isCheckboxOn == false;
- when select is in 'checkboxOn' state, the value should be as in request?
All of this should work also on Validation errors postback, and when new form is shown and on valid form case.
Also, I would like to avoid using JavaScript on client side.
Here is some code, which needed to be extended:
clas开发者_Python百科s MyFormObject {
private String selectValue;
private boolean isCheckboxOn;
...
}
and two Spring controller's method:
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView('/form.jsp', 'command', new MyFormObject());
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView processSubmit(BindingResult result, MyFormObject command) {
if (result.hasErrors()) {
return new ModelAndView('/form', 'command', command);
}
...
return new ModelAndView('redirect:/success.jsp');
}
If you want to exclude the checkbox field from your view when isCheckboxOn is set to false, you can surround the checkbox field with a c:if in your JSP:
<c:if test="isCheckboxOn">
(your checkbox <input> tag goes here)
</c:if>
To check the box by default, you can use Spring's form tag library to bind directly to the checkbox field in the model, or you can use another c:if
to add a checked
to your <input>
tag.
精彩评论