Connect thymeleaf with a list of objects

1

I am currently using these technologies

  • SPRING MVC
  • HIBERNATE
  • JPA
  • THYMELEAF
  • JACKSON JSON
  • create a form where you sent a recipe-type object

        @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private int id;
    private String nombre;
    
    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "receta_ingredientes", nullable = false)
    private Receta receta_ingredientes;
    

    and this class has 2 lists of classes (Ingredients and Steps) when generating the form because I do it this way

    where I ask you to separate them by commas (to separate them in the controller and make a list of everything) unfortunately you can not

    So I'm looking for a way for thymeleaf to automatically create a list of a class by seeing that the input has a comma

    something like this are my inputs:

    // Ingredients

    <input class="form-control" th:field="*{ingredients}" type="text" placeholder="Ingredientes">
    

    // Steps

    <input class="form-control" th:field="*{pasos}" type="text" placeholder="Ingredientes">
    

    some idea of how to connect this (that at the moment that thymeleaf sees a comma create another object to only generate a list of objects)

        
    asked by Monster 06.06.2018 в 07:52
    source

    1 answer

    1

    You need to create a class that contains a list List<String> pasos and% List<String> ingredientes .

    Within thymeleaf you iterate over them with a for:each="${ingrediente, i:ingredientes}

    The inputs you have to generate with post so that with some function js every time you press "," send the form with the data (or unless you put a variable of seción if I'm not wrong) and you add a new object to your list in a controller that you pass as a parameter.

    Then you show each element like this (Assuming you do it in a separate input and just to give an example of accessing the data within a list):

    <input type="text" th:field="${ingrediente[i.index]}"/ >
    

    Note that the i.index element lists the values in the list so that thymeleaf knows which object you are modifying. Without this the controller will not receive the changes.

      

    The code is direct. It may contain errors.

        
    answered by 08.06.2018 / 21:00
    source