首页 > 解决方案 > 如何在 Spring + Thymeleaf 中获取选定值以输入值(作为对象)?

问题描述

视图:modAnimal.html(这是视图的第一部分,之后是隐藏的 div 中的输入值)

<form th:action="@{/animales/preModAnimal}" th:object="${animal}" method="post" enctype="multipart/form-data" id="formPreModAnimal">

                    <!-- INPUT TIPO DE ANIMAL -->

                    <label>Animal</label>
                            <input type="radio" th:field="*{tipo}" th:value="*{tipo.PERRO}" required /> 
                            <label></label>

                            <input type="radio" th:field="*{tipo}" th:value="*{tipo.GATO}" required /> 
                            <label></label>

                    <!-- INPUT SEXO DEL ANIMAL -->

                    <label>Sexo</label>
                            <input type="radio" th:field="*{sexo}" th:value="*{sexo.MACHO}" required /> 
                            <label>♂️</label>

                            <input type="radio" th:field="*{sexo}" th:value="*{sexo.HEMBRA}" required /> 
                            <label>♀️&lt;/label>


                    <!-- INPUT SELECT ANIMAL -->

                    <label for="selectAnimal">Animal</label>

                        <select th:fragment="animales" id="selectAnimal" required
                            class="form-control">
                            <option value="" selected="selected">Selecciona animal</option>
                            <option th:each="i : ${animales}"
                                th:text="${i.emojiTipo} + ' ' + ${i.emojiSexo} + ' - ' + ${i.nombre} + ' - ' + ${i.raza} + ' - ' + ${i.provincia.provincia} + '  (' + ${i.poblacion} + ')'"
                                th:value="${i.id}"></option>
                        </select>

            </form>

根据选定的无线电,选择下拉菜单将加载所需的值。这是用 jQuery 完成的

funcionesCheck_jQuery.js

$(document).ready(function() {
  $('[name=tipo], [name=sexo]').change(function() {

    $("#selectAnimal").load('/animales/checktiposexo', $('#formPreModAnimal :input[type=radio]').serialize());

  });
});

这是控制器

AnimalesController.java

        @GetMapping("/modAnimal") public String pagMod(Model model) {

    Animal animal = new Animal();
    model.addAttribute("animal", animal);

    Sexo[] opcionesSexo = Sexo.values();
    model.addAttribute("sexos", opcionesSexo);

    Tipo[] opcionesTipo = Tipo.values();
    model.addAttribute("tipos", opcionesTipo);

    return "animales/modAnimal";
}

@GetMapping("/checktiposexo")
public String filtroTipoSexo(Model model, @RequestParam(name = "tipo", required = false) Tipo tipo,
        @RequestParam(name = "sexo", required = false) Sexo sexo) {

    List<Animal> listaAnimales;

    if (tipo == null && sexo == null) { // not working, i wanted this to act different, but nvm
        listaAnimales = animalesRepo.findAll();
        model.addAttribute("animales", listaAnimales);
    } else if (tipo != null && sexo == null) {
        listaAnimales = animalesRepo.findAllAnimalesByTipoOrSexo(tipo, sexo);
        model.addAttribute("animales", listaAnimales);
    } else if (tipo == null && sexo != null) {
        listaAnimales = animalesRepo.findAllAnimalesByTipoOrSexo(tipo, sexo);
        model.addAttribute("animales", listaAnimales);
    } else {
        listaAnimales = animalesRepo.findAllAnimalesByTipoAndSexo(tipo, sexo);
        model.addAttribute("animales", listaAnimales);
    }

    return "animales/modAnimal :: animales"; //I'm returning animales as fragment

}

然后,我想在帖子开头提到的同一视图中使用所选选项中给出的值填充一些输入值。

每次所选选项更改时,这些输入将再次重新显示。它们位于最初隐藏的 div (#modificarOculto) 中。

funcionesCheck_jQuery.js

$(document).ready(function() { 
$( "#modificarOculto" ).hide();
$("[name=tipo], [name=sexo], #selectAnimal").change(function() {
    $('#modificarOculto').hide('300');
    $("#selectAnimal").change(function() {

    inputSelectAnimal = $("#selectAnimal")[0];
    selectAnimal = $("#selectAnimal").val();

    if(selectAnimal>0){
    $('#modificarOculto').show('slow');


    }else if(selectAnimal==0){
        $('#modificarOculto').hide('slow');
    }


    });
});
});

请记住,这是开始视图下方的视图部分。我想在这些输入中加载选定的值。

modAnimal.html(再次)

        <div class="row cajita" id="modificarOculto">

            <form th:action="@{/animales/modAnimal-submit}" id="formModAnimal"
                th:object="${animal}" method="post" enctype="multipart/form-data">

                    <label >Nombre</label>
                        <input type="text" th:field="*{nombre}"  class="form-control"
                            placeholder="Nombre del animal" required minlength=3
                            maxlength=50 />

                    <label>Animal</label>
                            <input type="radio" th:field="*{tipo}" th:value="*{tipo.PERRO}"required /> 
                            <label></label>

                            <input type="radio" th:field="*{tipo}" th:value="*{tipo.GATO}" required /> 
                            <label></label>


                    <label>Sexo</label>
                            <input type="radio" th:field="*{sexo}" th:value="*{sexo.MACHO}" required /> 
                            <label>♂️</label>

                            <input type="radio" th:field="*{sexo}" th:value="*{sexo.HEMBRA}" required /> 
                            <label>♀️&lt;/label>

                    <!-- INPUT PROVINCIA ANIMAL -->

                    <label>Provincia</label>
                        <select id="provincia" name="provincia" required>
                            <option value="">Load the selected provincia</option>
                            <option th:each="i : ${provincias}" th:text="${i.provincia}"
                                th:value="${i.id}">
                        </select>

                        <button type="submit" id="botonModificar">Modificar</button>

            </form>
        </div>

我知道我需要一个表单来提交新值(“formModAnimal”),但是......我知道我不需要 begin 表单(“formPreModAnimal”)。我真的不知道我是否需要将整个视图(选择部分+输入部分)放在一个表单中。

如何将数据作为对象值从选定值发送到输入值?Thymeleaf 有什么聪明的方法吗?我可以将所选值与片段相关联并将其发送到“formModAnimal”表单并将其用作animal.attribute吗?那会很舒服。

你会怎么做?

我删除了所有引导程序 div 和类,以方便您进行概览。我希望你一切都清楚!

提前致谢!

标签: springselectinputthymeleafdropdown

解决方案


好的,我已经解决了。

这是我在funcionesCheck_jQuery.js中的新 jQuery 函数,我在 div $('#modificarOculto') 中加载所选下拉列表 $("#selectAnimal") 的序列化结果。
(我不知道为什么我不能只取下拉列表的id,或者为什么@RequestParam("selectAnimal") 不能直接从视图中取...)

$(document).ready(function() {
//$("#modificarOculto").hide();
$("[name=tipo], [name=sexo], #selectAnimal").change(function() {
    $('#modificarOculto').hide('300');
    $("#selectAnimal").change(function() {

        inputSelectAnimal = $("#selectAnimal")[0];
        selectAnimal = $("#selectAnimal").val();

        if (selectAnimal > 0) {
            $('#modificarOculto').show('slow');
            $('#modificarOculto').load('/animales/animalid', $("#selectAnimal").serialize());

        } else if (selectAnimal == 0) {
            $('#modificarOculto').hide('slow');
        }

    });
});
});

这是在控制器AnimalController.java中管理的:@RequestMapping("/animalid"),它将返回一个带有所选动物值的百里香片段。

@RequestMapping("/animalid")
public String getAnimalByID(@RequestParam(name = "selectAnimal", required = false) int idAnimal, Model model) {

    Animal animalModelo = new Animal();
    model.addAttribute("animal", animalModelo);

    Esterilizado[] opcionesEsterilizado = Esterilizado.values();
    model.addAttribute("esterilizados", opcionesEsterilizado);

    List<Provincia> listaProvincias = provinciasRepo.findAll();
    model.addAttribute("provincias", listaProvincias);


    Optional <Animal> animal = animalesRepo.findOneAnimalById(idAnimal);


    if (animal.isPresent()) {
        model.addAttribute("selectedAnimal", animal.get());
} else {
    // ERROR?
}


    return "animales/modAnimal :: selectedAnimal";
}

最后,这是我的观点的第二部分。我将 Thymeleaf 片段插入表单中,并将其用作对象。此表单也准备好将给定数据提交到数据库(映射)。现在我正在更新数据而不是插入。

<div class="row cajita" id="modificarOculto">

        <div class="col-md-9 offset-1">


            <form th:action="@{/animales/modAnimal-submit}" id="formModAnimal"
                th:object="${selectedAnimal}" method="post" enctype="multipart/form-data"
                class="was-validated" th:fragment="selectedAnimal">

                <th:block th:if="${selectedAnimal != null}">


                <!-- INPUT NOMBRE ANIMAL -->

                <div class="form-group row">
                    <label class="col-sm-2 col-form-label" for="nombre">Nombre</label>
                    <div class="col-sm-10">
                        <input type="text" th:name="nombre"  th:value="${selectedAnimal.getNombre()}"  class="form-control"
                            placeholder="Nombre del animal" required minlength=3
                            maxlength=50 />
                    </div>
                </div>

                <div class="form-group row">

                    <!-- INPUT TIPO DE ANIMAL -->

                    <label class="col-sm-2 col-form-label">Animal</label>
                    <div class="col-sm-1">
                        <div class="form-check">
                            <input type="radio" th:name="tipo" th:value="${selectedAnimal.tipo.PERRO}"  th:checked="${selectedAnimal.getTipo()} == ${selectedAnimal.tipo.PERRO}"
                                class="form-check-input" required > <label class="form-check-label"></label>
                        </div>

                        <div class="form-check">
                            <input type="radio" th:name="tipo" th:value="${selectedAnimal.tipo.GATO}" th:checked="${selectedAnimal.getTipo()} == ${selectedAnimal.tipo.GATO}"
                                class="form-check-input" required > <label class="form-check-label"></label>
                        </div>

                    </div>

                    <!-- INPUT SEXO DEL ANIMAL -->

                    <label class="col-sm-1 col-form-label">Sexo</label>
                    <div class="col-sm-1">
                        <div class="form-check">
                            <input type="radio" th:name="sexo" th:value="${selectedAnimal.sexo.MACHO}" th:checked="${selectedAnimal.getSexo()} == ${selectedAnimal.sexo.MACHO}"
                                class="form-check-input" required > <label class="form-check-label">♂️</label>
                        </div>
                        <div class="form-check">
                            <input type="radio" th:name="sexo" th:value="${selectedAnimal.sexo.HEMBRA}" th:checked="${selectedAnimal.getSexo()} == ${selectedAnimal.sexo.HEMBRA}"
                                class="form-check-input" required > <label class="form-check-label">♀️&lt;/label>
                        </div>

                    </div>

                    <!-- INPUT RAZA -->

                    <label class="col-sm-1 col-form-label" for="nombre">Raza</label>
                    <div class="col-sm-6">
                        <input type="text" th:name="raza" th:value="${selectedAnimal.getRaza()}" class="form-control"
                            placeholder="Raza del animal" required minlength=3 maxlength=100 />
                    </div>
                </div>


                <div class="form-group row">

                    <!-- INPUT FECHA DE NACIMIENTO -->

                    <label class="col-sm-2 col-form-label" for="fnac">Fecha de
                        nacimiento</label>
                    <div class="col-sm-4">
                        <input type="date" th:name="fnac" th:id="fnac" th:value="${selectedAnimal.getFnac()}" class="form-control"
                            min="1990-01-01" required />
                    </div>

                    <!-- INPUT ESTERILIZADO -->

                    <label class="col-sm-2 col-form-label">Esterilizado</label>
                    <div class="col-sm-4">
                        <th:block th:each="i : ${esterilizados}">
                            <div class="form-check">
                                <input type="radio" th:name="esterilizado" th:id="'esterilizado'+${iStat.index+1}" required
                                    th:value="${i}" class="form-check-input" th:checked="${selectedAnimal.getEsterilizado() == i}" > <label
                                    class="form-check-label" th:for="'esterilizado'+${iStat.index+1}"
                                    th:text="${#strings.capitalize(#strings.toLowerCase(i))}">Esterilizado</label>
                            </div>
                        </th:block>

                    </div>


                </div>

                <div class="form-group row">

                    <!-- INPUT PROVINCIA ANIMAL -->

                    <label class="col-sm-2 col-form-label" for="provincia">Provincia</label>
                    <div class="col-sm-4">
                            <select id="provincia" th:name="provincia" required
                                class="form-control">
                                <option th:each="i : ${provincias}" th:text="${i.provincia}"
                                    th:value="${i.id}"
                                    th:selected="${selectedAnimal.getProvincia().getId() == i.id}">
                            </select>

                            <!-- Si fuera un valor enum  <td><select th:field="*{provincia}">
                        <option th:each="i : ${provincias}" th:text="${i.toString()}"
                            th:value="${i}"></option></select></td>-->

                    </div>

                    <!-- INPUT POBLACION ANIMAL -->

                    <label class="col-sm-2 col-form-label" for="fnac">Población</label>
                    <div class="col-sm-4">
                        <input type="text" th:name="poblacion" th:value="${selectedAnimal.getPoblacion()}" class="form-control"
                            required minlenght=2 maxlength=50 />
                    </div>
                </div>



                <!-- INPUT FOTO ANIMAL -->

                <div class="form-group row">
                    <label class="col-sm-2 col-form-label" for="file">Foto</label>
                    <div class="col-sm-10">

                        <input type="file" name="file" accept="image/*"
                            class="form-control-file" id="validatedCustomFile" required />
                        <div class="invalid-feedback">Ningún archivo seleccionado</div>
                    </div>
                    <!-- INPUT FOTO EN LAS SOMBRAS -->
                    <label for="foto" style="display: none;">Foto</label> <input
                        type="text" th:name="foto"
                        th:value="${selectedAnimal.getFoto()}" maxlength=200
                        style="display: none;" />

                </div>

                <!-- INPUT DESCRIPCION ANIMAL -->

                <div class="form-group row">
                    <label class="col-sm-2 col-form-label" for="descripcion">Descripción</label>
                    <div class="col-sm-10">
                        <textarea class="form-control" required rows="5" cols="50"
                            th:name="descripcion" minlength=50 maxlength=255
                            th:text="${selectedAnimal.getDescripcion()}" th:value="${selectedAnimal.getDescripcion()}"
                            placeholder="Historia, personalidad, enfermedades, comportamiento con otras mascotas"></textarea>
                    </div>
                </div>


                <div class="form-group row">
                    <div class="col-sm-12">
                        <button type="submit" class="btn btn-success float-right"
                            id="botonUpdateAnimal">Actualizar</button>
                    </div>
                </div>

                <div th:if="${message}" th:text="${message}"
                    th:class="${'alert ' + alertClass}" ></div>

                </th:block>
            </form>

        </div>
    </div>

推荐阅读