简体   繁体   中英

How can I properly validate checkboxes with Spring MVC and ThymeLeaf?

I've created this critter that needs some validation:

在此处输入图片说明

This is the home.html file:

<!-- Modal -->
    <div id="vasoModal" class="modal">
        <div class="modal-content">
            <h4 class="modal-title">Vasito</h4>
            <h6>Seleccione hasta dos gustos</h6>
            <form th:action="@{/pedido}" name="vasitoForm" method="post">
                <table class="tabla">
                        <tr th:each="gusto : ${gustos}">
                            <td class="flavour" th:text="${gusto.nombre}"></td>
                            <td><input class="single-checkbox" type="checkbox" th:field="${gusto.id}"/></td>
                        </tr>
                </table>
                <button type="submit" class="btn-submit">Enviar Pedido</button>
            </form>
        </div>
    </div>

So I now need to validate which ones had been clicked and send this to the controller to validate:

var checkboxes = document.querySelectorAll('.single-checkbox');
var clicked = [];

checkboxes.forEach(elem => {
    elem.addEventListener('click', (event) => {
        event.stopPropagation();
        alert(elem.value);
        // My logic here was to add the clicked checkboxes to the clicked array and then send that to the controller to validate !!

Is this okey ? }); });

Well ... I've got two problems here ... the first one is that this line in the HTML is not working:

th:field="${gusto.id}"

I can't be able to bind the id of each "gusto" (flavour in spanish) to the checkboxes (this seemed like a nice solution).

The error I'm getting is the following:

Neither BindingResult nor plain target object for bean name 'gusto' available as request attribute

Well ... I've googled for that and found the solution, but not for my case sience I'm sending the "gustos" ArrayList to the view in the controller.

@RequestMapping(value = "/")
public String getAllProductos(ModelMap modelMap){
    List<Producto> productos = productoService.findAll();
    List<Gusto> gustos = gustoService.findAll();
    modelMap.put("gustos", gustos);
    modelMap.put("productos", productos);
    return "home";
}

So that problem is a bit weird !

Well ... the second problem, or question, is what I want to do after solving that ... it's commented in the JS file:

// My logic here was to add the clicked checkboxes to the clicked array and then send that to the controller to validate !!

Is this approach okey ?? Can someone help me on finding a better solution for the checkboxes error ??

...

For your first issue, th:field= needs a * instead of $ . Try changing th:field="${gusto.id}" to th:field="*{gusto.id}" - documentation here .

For your second, I'm not sure if this is the most graceful way to do it but it's been working for me. First, add a HttpServletRequest request (documentation here ) as a request parameter in your POST method. From that request , you can pull out a Map<String, String[]> , from which you can extract data. Then, you can do what you want with that data:

Map<String, String[]> dataFeed = request.getParameterMap(); // this pulls in the data from the checkboxes

for (Map.Entry<String, String[]> entry : dataFeed.entrySet()) { // this iterates through each entry from the data above
        for (String str : request.getParameterValues(entry.getKey())) { // this loops through the key for each entry 
            Long yourVar = Long.parseLong(entry.getKey()); // assigning the long version of that str to yourVar
            if (str.equals("Yes")) {
                Do something with yourVar // do something with it
            }
            daoObject.save(whatever you've done above);
        }
    }

In your case, maybe something like this would work:

@RequestMapping(value="saveGusto", method = RequestMethod.POST)
public String saveGusto(HttpServletRequest request) {

    Map<String, String[]> dataFeed = request.getParameterMap();

    for (Map.Entry<String, String[]> entry : dataFeed.entrySet()) {
        for (String str : request.getParameterValues(entry.getKey())) {
            Long gustoId = Long.parseLong(entry.getKey());
            Gusto gusto = gustoDao.findOne(gId);

            if (str.equals("some-value")) { // where some-value is value="some-value" on your checkbox
                // do something with the gusto
            }
            gustoDao.save(gusto);
        }
    }
}

Hope it gives you another avenue to explore, if nothing else!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM