3

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.

gursahib.singh.sahni
  • 1,559
  • 3
  • 26
  • 51

2 Answers2

2

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.

Community
  • 1
  • 1
Aboodz
  • 1,549
  • 12
  • 23
0

First thing that you need to do is create a controller for your page. From there you load into spring the information, in your case the list, in my case I used a ModelMap with a lot of different things.

@RequestMapping(value = "/assessment/", method = RequestMethod.GET)
public String showPage(ModelMap model, Principal principal) {
    [...]

    List<Assessment> list = new ArrayList<Assessment>();
    [...]
    model.addAttribute("assessments", list);
    [...]
    model.addAttribute(REQUEST_VIEW, new Gson().toJson(requestView));
    return "assessment"; //name of your page in spring config
}

Then put your configuration in Spring and your Pom. From there will be easy access to the information just using the names that you configure.

<table class="table-row-selected">
    <tbody>
    <div th:each="assessment : ${assessments}" th:remove="tag">
        <tr th:attr="ng-click='selectedAssessment(\''+ ${assessment.getTypeCode()}+'\' , \'' +${assessment.getName()} +'\', \'' +${assessment.isLookUpSaid()} +'\', \'' +${assessment.getLanguages()} +'\');', ng-mouseover='refreshDescription(\''+ ${assessment.getDescription()}+'\')'">
            <td><strong th:text="${assessment.getName()}"></strong></td>
        </tr>
    </div>
    </tbody>
</table>
Mahozad
  • 18,032
  • 13
  • 118
  • 133
David_Garcia
  • 622
  • 7
  • 15