mercredi 29 mai 2019

Java Spring with thymeleaf checkbox non checked is Empty instead of false

I have checkbox inside of my form :

  <div class="form-check form-check-inline">
                        <input type="checkbox" th:field="${search.titleIncl}" />
                        <label class="form-check-label" th:for="${#ids.next('covered')}">Title</label>
                    </div>

This checkbox by default should be on since search object has this value assigned as true. This works fine. What i expected from thsi checkbox is to send either true or false when its checked/unchecked. What i got now is True if its checked and nothing when not checked. That his a bit of an issue for me :

In controller:

@GetMapping(value = Utils.MAPPING_INDEX)
public ModelAndView index(@RequestParam("titleIncl") Optional<Boolean> titleIncl) {
    ...calling fillSearch inside of body....
}


private Search fillSearch(Optional<Boolean> titleIncl..) {

        Search search = new Search();

        //Get seach value if nothing provided give me default.
        search.setTitleIncl(titleIncl.orElse(search.isTitleIncl()));
        ...

        return search;
}

Whole point of this form is to get user select what parts of the object he wants to search : enter image description here

So if he unselects checkbox and i dont send FALSE in optional, I run into problem.

When user initialy goes into the site, he doesnt send any of these parameters so it behaves fine by setting everything to true. Bud once he initiates search and deselects parts he doesnt wanna search in, he still ends up with defaults and searches in everything.

So is there a simple way of sending Optional FALSE if checkbox value is not selected?

Note :

  • By simple i mean without creating additional endpoint for this form search and no Javascript :)

  • And yes the form is under GET request




Aucun commentaire:

Enregistrer un commentaire