Add items dynamically to a list using Thymeleaf

0

In my application, I have a form for adding a determining object to the database. In this object I have a list of other objects. For example, it is as if the object that I am registering is a Sale and the list is Sales Item. How to add multiple sale items for sale?

    
asked by anonymous 22.05.2017 / 01:31

1 answer

0

Looking at the documentation of thymeleaf, I can do this. I will give the example of my project,

This my entity, I will create dynamic fields from the courseTurno list.

If all your repository, service and configuration, routes, ... have finished I will only inclement this in the controller. ~

In your request Mapping to the form you need to list the arrow because if it will not load it would do and will only implement when you click the button to add a list.

    @PreAuthorize("hasAuthority('PERM_CURSO_CADASTRAR')")
    @RequestMapping("/novo")
    public ModelAndView cadastrarCurso() { // crio e seto a lista quando redireciono para o formulário
    ModelAndView mv = new ModelAndView();
    mv.setViewName("/curso/formulario");

    Curso curso = new Curso();
    CursoTurno cursoTurnos = new CursoTurno();
    cursoTurnos.setCurso(curso);
    curso.getCursoTurnos().add(cursoTurnos);
    mv.addObject("curso", curso);

    return mv;
    }

Still in my controller I will create this method for when I click the button in my case the value of the parameter and "addRow" it implement the fields, NOTHING OF JAVA SCRIPT. thymeleaf and very good I recommend reading all the documentation + springMVC

/ ***************************      * Dynamic Methods      eur-lex.europa.eu eur-lex.europa.eu

@RequestMapping(value = "/novo", params = {"addRow"}, method = RequestMethod.POST)
public String addRow(final Curso curso, @RequestParam("addRow") String addRow, final BindingResult bindingResult) {

    CursoTurno cursoTurno = new CursoTurno(); // crio minha list
    cursoTurno.setCurso(curso); // set ela
    curso.getCursoTurnos().add(cursoTurno);
    return "/curso/formulario"; // retorno com a nova list
}

@RequestMapping(value = "/novo", params = {"removeRow"}, method = RequestMethod.POST)
public String removeRow(
        final Curso curso, final BindingResult bindingResult,
        final HttpServletRequest req) {
    final Integer rowId = Integer.valueOf(req.getParameter("removeRow"));
    curso.getCursoTurnos().remove(rowId.intValue());
    return "/curso/formulario";
}

In NA view we will create a ROW, in thymeleaf rowStat.index and count started with 0. ALL THAT RELATES TO THE LIST VALUE needs to be '[ $ {rowStat.index} ].' between the object and its attribute, A lot in that part and part of my private validation, character limit in the field with JS and error msg.

  <!-- INICIO - Curso Turno -->
                        <div class="form-group"   th:each="cursoTurnos, rowStat : *{cursoTurnos}" th:if="${rowStat.index} &lt; 3">
                            <div class="col-sm-5"  >
                                <div class="form-group"
                                     th:class="${#fields.hasErrors('cursoTurnos[__${rowStat.index}__].quantidadeVagas')} ? has-error">
                                    <label class="control-label required"
                                           th:text="|#{mensagem.quantidadeDeVagas}|" >Quantidade de Vagas</label>
                                    <input type="text"  class="form-control input-sm" th:id="quantVagas_ + ${rowStat.index}"
                                           th:field="*{cursoTurnos[__${rowStat.index}__].quantidadeVagas}"  onkeydown="limita(this);" ng-model="numero.valor"  onkeyup="somenteNumeros(this);"  min="0" />
                                    <label class="error"
                                           th:if="${#fields.hasErrors('cursoTurnos[__${rowStat.index}__].quantidadeVagas')}? fieldError"
                                           th:errors="*{cursoTurnos[__${rowStat.index}__].quantidadeVagas}"></label>
                                </div>
                            </div>
                            <div class="col-sm-5" >
                                <div class="form-group" th:classappend="${#fields.hasErrors('cursoTurnos[__${rowStat.index}__].turno')} ? has-error">
                                    <label class="control-label required" for="turno" th:text="#{mensagem.turno}">Turno</label>
                                    <select class="form-control " id="turno" th:field="*{cursoTurnos[__${rowStat.index}__].turno}" data-plugin-selectTwo="">
                                        <option selected="selected" value="" th:text="#{mensagem.selecione}"></option>
                                        <option th:each="turno: ${getAllTurnos}" th:value="${turno.id}" th:text="#{'mensagem.'+ ${turno.nome}}" id="turno"></option>
                                    </select>
                                    <label class="error" th:if="${#fields.hasErrors('cursoTurnos[__${rowStat.index}__].turno')}? fieldError" th:errors="*{cursoTurnos[__${rowStat.index}__].turno}">
                                    </label>
                                </div>
                            </div>
                            <div class="col-sm-1">
                                <button class="btn btn-danger padding-buttons" type="submit" name="removeRow" th:value="${rowStat.index}"
                                        th:if="${rowStat.index} ge 0 and ${#lists.size(curso.cursoTurnos) ne 1}" > // LOGICA PARA O BOTÃO DE REMOÇÃO SO APAREÇA QUANDO AH 2 LIST E EU POSSO EXCLUIR O PRIMEIRO VALOR, DESENVOLVIDA PELO MEU AMIGO (CAIRO,ENG. COMPUTAÇÃO,UNIEVANGÉLICA-GO,2017).
                                    <i class="fa fa-minus" style="color: white;"></i>
                                </button>
                            </div>
                        </div>

OFF ROW AND MY BUTTON TO ADD it to when ah 3 list, "& lt;" in thymeleaf it means

25.05.2017 / 13:56