0

How should I create an html form to bind data with Map field in my DTO object? Here is my DTO class:

@Data
public class SimpleBTO {
    private String field1;
    private Map<String,Integer> mapField;
}

So once again, how to create a form in thymeleaf for such element?

jeff porter
  • 6,560
  • 13
  • 65
  • 123
  • Try googling "Thymeleaf Map Form" Also see, https://stackoverflow.com/questions/33915358/thymeleaf-map-form-binding – geneSummons Feb 13 '18 at 18:25

1 Answers1

0

If you know the keys:

<form th:object="${dto}">
  <input type="text" th:field="*{mapField['key']}" />
</form>

Similarly, you can loop over all the values:

<form th:object="${dto}">
  <input th:each="entry: ${dto.mapField}" type="text" th:field="*{mapField['__${entry.key}__']}" />
</form>
Metroids
  • 18,999
  • 4
  • 41
  • 52
  • And what if i don't know they keys/ want to add new entries? – tomek tomek Feb 13 '18 at 20:09
  • @tomektomek -- works the same way... the two examples above work regardless of whether they already exist in the map or not (except in the second example, `${entry.key}` would instead be an expression that resolves to the string key of the entry you want to save. – Metroids Feb 13 '18 at 20:35