繁体   English   中英

如何使用Spring MVC和ThymeLeaf正确验证复选框?

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

我创建了这个需要进行验证的生物:

在此处输入图片说明

这是home.html文件:

<!-- 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>

因此,我现在需要验证单击了哪些,然后将其发送到控制器以进行验证:

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 !!

这是好吗? }); });

好吧……我这里有两个问题……第一个是HTML中的这一行不起作用:

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

我无法将每个“ gusto”(西班牙语风味)的ID绑定到复选框(这似乎是一个不错的解决方案)。

我收到的错误如下:

Bean名称“ gusto”的BindingResult或普通目标对象都不能用作请求属性

好吧...我已经为此进行了谷歌搜索并找到了解决方案,但是由于我的案例原因我没有将“ gustos” ArrayList发送到控制器中的视图。

@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";
}

所以这个问题有点怪!

好吧...第二个问题或问题是解决该问题后我想做什么...它在JS文件中已注释:

//我的逻辑是将单击的复选框添加到单击的数组,然后将其发送到控制器以进行验证!

这种方法好吗? 有人可以帮我找到更好的复选框错误解决方案吗?

...

对于第一个问题, th:field=需要一个*而不是$ 尝试将th:field="${gusto.id}"更改为th:field="*{gusto.id}" - 此处的文档。

对于您的第二个,我不确定这是否是最优雅的方法,但是它一直在为我工作。 首先,在POST方法中添加HttpServletRequest request此处为文档)作为请求参数。 从该request ,您可以提取Map<String, String[]> ,从中可以提取数据。 然后,您可以使用该数据执行所需的操作:

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);
        }
    }

在您的情况下,也许类似的事情会起作用:

@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);
        }
    }
}

希望它能为您提供其他探索的途径!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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