Search code examples
javaspringspring-bootthymeleaf

In Spring Boot Thymeleaf , how to pass list of object to th:value ??? I would like to create tag input


  1. Here is my form html
     <div class="card-body">
           <form action="@{/orgCategoryTag/create}"  method="POST">
              <div class="form-group">
                <label for="form-tags-1" class="text-dark font-bold">Add new tags</label>
                <input id="form-tags-1" name="tags-1" type="text" th:value="${tags}">
              </div>
              <a
                  type="button"
                  class="btn btn-success" href="#"
                  data-placement="top" title="Tooltip on top">Add
              </a>
           </form>
        </div>
  1. Here is Get mapping for rendering form
    @GetMapping(value = "/form")
        public String categoryForm(Model model, BindingResult result) {
            Long testId = (long)1;
            OrgCategory orgCategory = new OrgCategory();
            List<OrgCategoryTagModel> orgCategoryTags = orgCategoryTagRestController.getAllByCategoryId(testId);
            model.addAttribute("category", orgCategory);
            model.addAttribute("tags", orgCategoryTags);
            model.addAttribute("add", true);
            return "orgCategoryForm";
        }

Solution

  • For displaying a list of options (tags in your context), please use a combo-box, they are better suited to display a list of options.

    <select>
          <option
               th:each="tag: ${tags}"
               th:text="${tag.name}"
               th:value="${tag.id}"
          />
    </select>
    

    <select> is the tag for creating a combobox and <option> are the different options available in the combobox. I have used a for each loop to create different options for the combobox where tag represents your object OrgCategoryTagModel.

    I do not know your object OrgCategoryTagModel, but I am assuming you want to display the name of the tag (tag.name) and use the id of OrgCategoryTagModel (tag.id) as the value to be saved when making a selection.