Nikita
Nikita

Reputation: 1

Send object from th:each loop to controller

I have form and corresponding controller to which list of objects is passed.

entity classes:

    @Entity
    public class Entity1
       @Id
       @Column(name="id")
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       private long id;
    
       @ManyToOne(cascade = CascadeType.PERSIST)
       @JoinColumn(name = "entity2_id")
       private Entity2 entity2Field; 
    
    @Entity
    public class Entity2
    
       @Id
       @Column(name="id")
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       private long id;
    
       @Column(name="name")
       private String name; 

controller:

    @GetMapping(value="/create")
    puplic String show(Model entity1Model, Model entity2Model){
        
        entity1Model.addAttribute("entity1", new Entity1());
        List<Entity2> list= entity2Repository.findAll();
        entity2Model.addAttribute("entity2list", list);
        return "form"
        }

    @PostMapping(value="/create/new")
    public String save(Entity1 entity1, @RequestParam(name="entity2list) String somevalue{
        Entity2 entity2= entity2Repository.findByName(somevalue);
        entity1.setEntity2Field(entity2)
        entity1Repository.save(entity1)
        return "redirect:/"  
    }

form:

<form method="post" th:action="@{create/new}">
  <select class="form-control" name="entity2list">
    <option th:each="ent2:${entity2list} 
      th:value="${ent2.name} th:text="${ent2.name}>
  </select>
  <button type="submit"></button>
</form>

I suppose that thymeleaf th:each loop variable in form can't be th:object=${ent2} (cause if i do this way, select form return null). Whereas th:value="${ent2.name} return string value. So i had to send @RequestParam(th:value) to "save" method. But in this case i had to do additional request to database, to get Entity2 object and set it to Entity1.

How can i get entity object in some way like:

<form method="post" th:action="@{create/new}">
  <select class="form-control">
    <option th:each="ent2:${entity2list} 
      th:object="${ent2} th:text="${ent2.name}>
  </select>
  <button type="submit"></button>
</form>

and send (@ModelAttribute("ent2")Entity2 ent2 instead of @RequestParam) to the "save" method to avoid redundant request to database?

Upvotes: 0

Views: 722

Answers (1)

Nikita
Nikita

Reputation: 1

i have solved the issue th:field="*{entity2Field} works like setter https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#creating-a-form

<form method="post" th:action="@{create/new}" th:object="${entity1}">
      <select class="form-control" th:field="*{entity2Field}>
        <option th:each="ent2:${entity2list} 
          th:value="${ent2} th:text="${ent2.name}></option>
      </select>
      <button type="submit"></button>
</form>

Upvotes: 0

Related Questions