猿问

如何使用 ThymeLeaf 将对象的属性绑定到隐藏字段?

HTML - ThymeLeaf 模板:


<form th:action="@{/gustos}" method="post" th:object="${gusto}">

    <div class="col s12 l8">

                    <select th:field="*{categoria}">

                        <option value="" disabled="disabled">Categoria</option>

                        <option value="Dulces de Leche">Dulce de Leche</option>

                        <option value="Cremas">Cremas</option>

                        <option value="Chocolates">Chocolates</option>

                        <option value="Frutales">Frutales</option>

                    </select>

    </div>

</form>

这是我的 Java Gusto类属性:


    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private int id;


    @Column

    private int idCategoria;


    @Column

    private String categoria;


    @Column // opcional (name="")

    private String nombre;

如果用户选择第一个选项 (Dulce de Leche),我需要Gusto类中的int idCategoria值取值为 1,第二个为 2,第三个为 3,第四个为 4,但是我不知道如何用 ThymeLeaf 做到这一点!!此逻辑基于类别属性,如果类别等于某个名称,则类别 ID 将是某个数字...示例:如果类别等于 'Dulces de Leche',则类别 ID 应为 '1' !!!


¡ 注意我在表单顶部使用对象绑定!


我试过这个:


  <div th:field="*{idCategoria}">

            <div th:switch="*{categoria}">

                <input type="hidden" th:case="'Dulces de Leche'" value="1" />

                <input type="hidden" th:case="'Cremas'" value="2" />

                <input type="hidden" th:case="'Chocolates'" value="3" />

                <input type="hidden" th:case="'Frutales'" value="4" />

            </div>

  </div>

但它不起作用!!!我想做模板中的逻辑!


我该怎么做 ?


陪伴而非守候
浏览 528回答 2
2回答

幕布斯6054654

您可以使用它jQuery来完成此操作。只需使用您缺少的字段创建一个新的隐藏输入即可。您的代码将类似于以下内容。首先您的新输入和类别的选择更改<input id="id" th:field="*{id}" hidden="hidden"/><select id="categorias" th:field="*{categoria}">&nbsp; &nbsp; <option value="" disabled="disabled">Categoria</option>&nbsp; &nbsp; <option value="Dulces de Leche">Dulce de Leche</option>&nbsp; &nbsp; <option value="Cremas">Cremas</option>&nbsp; &nbsp; <option value="Chocolates">Chocolates</option>&nbsp; &nbsp; <option value="Frutales">Frutales</option></select>现在你的 jQuery$('#categorias').on('change', function() {&nbsp; &nbsp; var value = $(this).val();&nbsp; &nbsp; if(value === "Dulce de Leche") {&nbsp; &nbsp; &nbsp; &nbsp; $('#id').val(1);&nbsp; &nbsp; }&nbsp; &nbsp; // Now you just fill the rest.})所以现在,每次更改类别时,都会为 id 添加一个新值。希望能帮助到你!如果您需要其他任何东西,请告诉我。

慕无忌1623718

试试这个:<select th:field="*{categoria}">&nbsp; &nbsp; <option th:value="" disabled="disabled">Categoria</option>&nbsp; &nbsp; <option th:value="1" th:text="Dulces de Leche"></option>&nbsp; &nbsp; <option th:value="2" th:text="Cremas"></option>&nbsp; &nbsp; <option th:value="3" th:text="Chocolates"></option>&nbsp; &nbsp; <option th:value="4" th:text="Frutales"></option></select>这样,当您通过后端检索值时,它将是 1、2 或 3
随时随地看视频慕课网APP

相关分类

Java
我要回答