Search code examples
javaspring-mvcthymeleaf

Thymeleaf - Input Dynamic List Of String


I want to add a dynamic list of input fields from the user. Combine those different inputs and pass them as list from the view to the controller. This is my domain class

public class HTMLPage {

    @Size(min = 3)
    @NotNull
    private List<String> ingredients;
    @Size(min = 5)
    @NotNull
    private List<String> method;
    @Size(min = 3)
    @NotNull
    private String recipeName;
    //getter setters

 }

I am completely new to thymeleaf. I have gone through all possible tutorials. There are different ways how to iterate the list but I cannot find a way to dynamically input list of strings and send the complete HTMLPage object to my controller.


Solution

  • Actually, it's more about Spring binder rather than thymeleaf. Whenever the user adds a new input, then by using JavaScript you append <input name="ingredients[0]" /> to the form. After that every time you increment the index by 1, So, the next append will be <input name="ingredients[1]" />. and so forth. Refer to this answer for more info.