Thymeleaf-未在th:each中设置复选框的Checked属性,或者如何正确还原复选框的列表,其中某些复选框先前已被选中 [英] Thymeleaf - Checked attribute of checkbox is not set in th:each OR how to properly restore a list of checkboxes some of which were previously checked

查看:1767
本文介绍了Thymeleaf-未在th:each中设置复选框的Checked属性,或者如何正确还原复选框的列表,其中某些复选框先前已被选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我想创建一个新的Risk(Risk对象的实例),创建后,我想显示5个复选框和3个单选按钮。选择的选项特定于Risk对象的每个实例。

In my app I want to create a new Risk ( an instance of Risk object ) and when it is created I want to display 5 checkboxes and three radio buttons. Selected options are specific to each instance of Risk object.

稍后我想显示所有添加的风险的列表,并在每个风险上使用编辑选项按钮。我希望我的应用还原特定于选定风险的视图(单击选定风险的编辑按钮时)-带有风险名称,所有复选框和单选按钮均已选中。而且我希望能够再次编辑这些复选框选择,以便所有新更改都能正确反映在MySQL中。

Later I want to display a list of all added Risks with an Edit option button on each Risk. I want my app to restore the view specific to a selected Risk ( when an Edit button on a selected risk is clicked ) - with Risk name, all checkboxes and radio-buttons checked as selected previously. And I want to be able to edit these checkbox selections again so that all new changes were properly reflected in MySQL.

作为Thymeleaf中的新手,我做了以下工作:

As a newbie in Thymeleaf I did the following:

<div th:each="top : ${topic}">
    <input type="checkbox" th:field="*{topic}" th:checked="${top.checked}" th:value="${top.name}"/><label th:text="${top.name}">Something is wrong !</label>
</div>

我确定Controller和Hibernate / MySQL部分正常工作(我使用Logs进行了检查)。

I am sure that Controller and Hibernate/MySQL part works properly ( I checked using Logs ).

这很好用-但仅当我仅选中一个复选框(最初添加风险时)。

This works just fine - but only if I have selected only one checkbox ( initially when I added a risk ).

如果我选择了多个复选框(添加风险时),然后又选择了此风险,则不会选中任何复选框。

If I select more than one checkbox (when adding a risk) and later select this risk for editing no checkboxes are checked.

有什么问题吗?

推荐答案

经过一番研究,我在Thymeleaf的文档中找到了以下文字:

After some research I found the following text in Thymeleaf’s documentation:

…th :field会解决这个问题,并会在相应的输入标签中添加一个check = checked属性。。

"… th:field would have taken care of that and would have added a checked="checked" attribute to the corresponding input tags.".

我也找到了本指南:

Also I found this guidance :

http://forum.thymeleaf.org/The-checked-attribute-of-the-checkbox-is-not-set-in-th-each-td3043675.html

然后,我设法开发了几个小型应用程序,我想分享我发现的内容,并希望它能对某人有所帮助。
(可能对有经验的人来说太详细了,但我希望所有人都清楚)

Then I managed to develop a couple of small apps and I want to share what I found out and hope it will help someone. ( may be it is too detailed for experienced people, but I want it to be clear to all )

我不想重复已经存在的内容上面提到的Thymeleaf的论坛页面(请参阅管理员的第一个答复/说明以获取详细信息-论坛主题中的第二个)-只是想作一个小结并强调几点:

I do not want to repeat what is already in the above-mentioned Thymeleaf’s forum page ( see Administrator’s first response / explanation for detail - second in forum thread ) - just want to make a small summary and stress out few points:


  • 您确实不需要在使用th:each时添加已选中;

  • you indeed do not need to add ‘checked’ when using th:each;

您必须添加: field = {…},应具有与复选框相关的模型类中的字段名称(Thymeleaf称为表单支持bean-th:object)。有关更多信息:上面我说过,我的表单支持bean是Risk.java。并且对于每个Risk对象实例,选中的复选框代表特定于此Risk实例的主题。然后,选定的主题将分配给Risk.java实例的主题字段(因此,保存实例时,将在MySQL的相关表中)。在我的情况下,该字段的名称应位于th:field = {…}内,如th:field = * {topic}。当您选中复选框时,Thymeleaf将使用其setTopic方法将所选值保存到Risk.java的topic字段中,当需要还原视图时,Thymeleaf将使用Risk.getTopic方法获取有关较早选择的项目的信息。

you must add th:field="{…}" which should have the name of the field in your model class (referred by Thymeleaf as form-backing bean - th:object ) to which checkboxes are related. More on this: I stated above that my ‘form-backing bean’ was Risk.java. And for each Risk object instance the selected checkboxes represent topics(s) specific to this Risk instance. And selected topics are assigned to field ‘topic’ of Risk.java's instance (and hence in related table in MySQL when instance is saved). That field’s name should go inside th:field="{…}" as th:field="*{topic}" in my case. When you select checkboxes Thymeleaf will save selected values to Risk.java’s topic field using its setTopic method and when it needs to restore view Thymeleaf will use Risk.getTopic method to get info on earlier selected items.

复选框(或单选按钮)的所有值都应来自另一个来源-如果您需要一组静态复选框,或者需要动态生成复选框,则可以为Enum一个类(我的应用程序需要一组静态的复选框,但我决定也尝试创建一个动态的复选框-请在下面查看指向我的Github存储库的链接以查看我设法开发的代码)。因此,对于我的应用程序,我创建了一个Enum主题,其中所有值都为复选框,而Enum Types的所有值都为单选按钮。然后在您的控制器类中,应将所有值添加到Model的属性中-我使用枚举时是这样做的:

all values of checkboxes (or radio-buttons ) should come from another source - it could be an Enum if you need a static set of checkboxes or if you need checkboxes to be dynamically generated you can use a class ( I needed static set of checkboxes for my app, but I decided to try to create a dynamic one as well - see links to my Github repo’s below to see the code I managed to develop ). So for my app I created an Enum Topics with all values for checkboxes and Enum Types with all values for radio-buttons. Then in your controller class you should add all values to Model’s attribute - I did this as I used an Enum:

model.addAttribute("topics", Topics.values());
model.addAttribute("types", Types.values());


(如果需要动态变量,请执行以下操作:

(if you need dynamic ones do the following:

    model.addAttribute("topics", topicsService.findAll());
    model.addAttribute("types", typesService.findAll());

然后您应该有类似的内容:

Then you should have something similar to:

    <div>
            <div th:each="top : ${topics}">
                <input type="checkbox" th:field="*{topic}"  th:value="${top.id}"/><label th:text=" | &nbsp; ${top.name}|">Something is wrong !</label>
            </div>
    </div>

    <div>
            <div th:each="typ : ${types}">
                <input type="radio" th:field="*{type}"  th:value="${typ.id}"/><label th:text="| &nbsp; ${typ.name} |">Something is wrong !</label>
            </div>
    </div>

其中:


    如前所述,
  • :th:field = {topic}对应于表单支持的模型类-Risk.java的字段。与th:field = {type}相同;

  • as mentioned, th:field="{topic}" corresponds to form-backing Model class - Risk.java’s field. Same for th:field="{type}" ;

th:each = top:$ {topics}中的主题应该与您在控制器中提供的属性名称匹配。

topics in th:each="top : ${topics}" should match with attribute name you provided in controller.

最重要的部分是th:field = * {topic}应该返回一个数组。

And the MOST important part is that th:field="*{topic}" should return an array.

th:field = * {topic}返回一个选定项的数组,并且th:每个返回所有选项的数组Thymeleaf现在应该能够在第一个数组中的值匹配时将复选框/单选按钮标记为已选中

th:field="*{topic}" returning an array of selected items and th:each returning array of all options Thymeleaf should now be able to mark checkboxes / radio buttons as checked when values in first array match values in second array.

由于单选按钮,您只能选择一个选项th:field = * {type}实际上并不返回数组-

Since in case of radio buttons you can select only one option th:field="*{type}" does not actually return an array - it returns only one item. But in case of checkboxes it should be an array - so the ‘topic’ field in Risk.java must return an array.

为此,我们需要返回一个项目,但是如果是复选框,它应该是一个数组-因此Risk.java中的 topic字段必须返回一个数组。一个convert依者er-名为例如实现AttributeConverter的StringListConverter…。

For this we need a converter - a class named e.g. StringListConverter that implements AttributeConverter….

(我在这里了解了如何操作。如果不在www.stackoverflow.com中此答案,我将无法最终确定此应用程序并且不会写所有这些:
https://stackoverflow.com/a/34061723/6332774

( I learned how I can do it here. If not this answer in www.stackoverflow.com I would not be able to finalyze this app and would not be writing all this: https://stackoverflow.com/a/34061723/6332774 )

然后在表单支持模型类中-Risk.java在我的情况下,您需要执行以下操作:

Then in your form-backing model class - Risk.java in my case you need to do something like :

@Convert(converter = StringListConverter.class)
private List<String> topic = new ArrayList<>();

private String type;

类型可以简单地是字符串。

Type can simply be a String.

就是这样。

(我想以表格形式显示复选框,指示所需的列数-我可以做到,但是我不确定它的清洁程度或

( I wanted to display checkboxes in table form indicating number of columns needed - I could do it, but I am not sure how clean it is or how safe it is. Related code is in riskformtable.html in example project linked below.

我在这里发布了一个相关问题- Thymeleaf-使用th:each时以表格形式显示复选框是我在做什么是安全的吗?

I posted a related question here - Thymeleaf - Displaying checkboxes in table form when using th:each - is what I am doing safe?

我还想对所有风险项目使用不同的颜色,在风险列表中具有连续的序号-它在index.html中

Also I wanted to use different color for all risk items with even sequential number in my risk’s list - it is in index.html

使用下面的链接查看完整的示例代码)

See full example code using links below )

到我的GitHub存储库的链接:

Links to my GitHub repos:

带有动态生成的复选框的示例:< a href = https://github.com/aripovula/Spring-Thymeleaf_dynamic_checkboxes_n_radio-buttons rel = noreferrer> https://github.com/aripovula/Spring-Thymeleaf_dynamic_checkboxes_n_radio-buttons

example with dynamically generated checkboxes : https://github.com/aripovula/Spring-Thymeleaf_dynamic_checkboxes_n_radio-buttons

这篇关于Thymeleaf-未在th:each中设置复选框的Checked属性,或者如何正确还原复选框的列表,其中某些复选框先前已被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆