Checkbox values do not bind into object when false?

27,575

Solution 1

Spring has a built in workaround.

Simply add this additional hidden field to the form:

<input type="hidden" value="on" name="_active"/>

The parameter with a leading underscore is some kind of marker, to indicate the existence of a checkbox parameter with the same name, but without the underscore.

Spring should now set lesson.active to false if only _active=on is submitted.

Solution 2

I think that you should use springframework tags - why are you using plain html? If your view is JSP page just import:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

and then you can use:

<form:checkbox path="path" label="label" />

which handles the problem.

Solution 3

You can use spring framework tags like it will automatically set you selected value to bean class and then it will be very easy to get its value in your controller class.

on path you need to put your bean variable name

and to use this you need to give command name to your form and use that command name to bind your bean object to that jsp

model.addAttribute("command name" , bean object) use this in your controller to bind object.

Share:
27,575
Hoàng Long
Author by

Hoàng Long

I'd like to describe myself as an adventurer who seeks to explore new knowledge. But actually, I'm just an ordinary people, struggling hard to make the life a little better.

Updated on February 26, 2020

Comments

  • Hoàng Long
    Hoàng Long about 4 years

    I used ModelAttribute to bind object in Spring web application.

    Once I notice that, in case an object has an boolean value A is true, its value will not be updated if we uncheck A's checkbox.

    For example, I have a Lesson object which has the attribute "active" = true. In "Edit Lesson" view, I make a checkbox which bind into "active". Things work well if the checkbox is checked (the binding object reflect the changes), but the object lesson will not change if we un-check the checkbox.

    Further study tells me that's because the checkbox value may not get submitted by browser (this is an in-design of HTML). So I have to use the ugly request.getParameter to check if the value is set.

    I just come by this question, and I see that asp.net mvc provide a way to work around it more elegantly. I think Spring must provide something similarly. Does anyone know how to do that?

    Following is my code:

    Controller code:

        @RequestMapping(value="/test", method = RequestMethod.POST)
        public String processEditLesson(@Valid Lesson lesson, BindingResult bindingResult, Model model) {
            System.out.println("Lesson is active: " + lesson.isActive()); // still "true" even if the checkbox is unset
    
            // Current work-around
            String isActive = request.getParameter("active");
            if (StringUtils.isNotNullOrEmpty(isActive)) {
                lesson.setActive(true);
            } else {
                lesson.setActive(false);
            }
            ...
        }
    

    View code:

    <form id="lesson" class="EditorForm" action="${rc.getContextUrl('/test.html')}" method="post" >
    
        <fieldset>
            <legend><@spring.message code="lesson.edit"/></legend>
            <@spring.formHiddenInput "lesson.id" />
            <@spring.formHiddenInput "lesson.studio.id" />
    
            <div class="Entry">
                <label for="name"><@spring.message code="lesson.message"/></label>
                <@spring.formInput "lesson.message" />
                <span class="ErrorMessage"><@spring.showErrors "<br/>" /></span>
            </div>
    
            <input type="checkbox" name="active" checked="checked" />
            <label for="active">${rc.getMessage('lesson.active')}</label>
    
            <input type="submit" value="<@spring.message code='common.update' />" />
        </fieldset>
    </form>
    
  • Hoàng Long
    Hoàng Long over 12 years
    Thanks, how do you know this way? I mean, I have searched a lot without finding any results. Just a little fix: I need to use "_active" instead "_lesson.active" to make it work.
  • Ralph
    Ralph over 12 years
    I have corrected the names. -- How I know it? I am doing Spring MVC in a professional way for more then 5 years. When I started this question was very popular. BTW: If you use the Spring checkbox jsp tag, then the hidden filed is already included.
  • Hoàng Long
    Hoàng Long over 12 years
    thanks for the jsp method, but actually I use freemarker. Freemarker macro formCheckBoxes does not have any example to go with it
  • Hoàng Long
    Hoàng Long over 12 years
    sorry, but I DON'T use jsp. I use freemarker, and if you know how to write it in freemarker, please let me know. For now, I used my custom macro instead.
  • abiieez
    abiieez almost 11 years
    Useful information. However I find if the element name contains . the value will not change automatically. I guess I'll have to change it using JavaScript
  • sedran
    sedran over 7 years
    Thanks for the useful information. I've always wondered why parameters starting with underscore exist.