CT11
CT11

Reputation: 73

Spring form th:object and th:field

I would like to capture just the input name to the spieler object.

<form th:action="@{/login}" method="post" th:object="${spieler}">
     <label for="nameInput" class="mt-4">Tragen einfach deinen Name ein, um deine Reise zu beginnen :</label>
     <br>
     <div class="d-flex justify-content-center my-4" >
          <input type="text" class="form-control" id="nameInput" th:field="*{name}">
          <button type="submit" class="btn-secondary ">Beginnen</button>
     </div>
</form>

this is the controller

@PostMapping("/login")
public String login (@ModelAttribute("spieler") Spieler spieler){
    spielerRepository.save(spieler);
    return "redirect:/";
}

and the Spieler-class:

@Data
public class Spieler {
     private int id;
     private String name;
     private int level;
     private int punkte;

     public Spieler (String name){
        this.name = name;
        this.level = 1;
        this.punkte = 0;
     }
}

the thymeleaf don't do that. How can i please solve this problem ? Sorry for bad English !

Upvotes: 0

Views: 1793

Answers (1)

Wim Deblauwe
Wim Deblauwe

Reputation: 26858

It will be easier to create a dedicated object for the form parameters. For instance, you could create a class LoginFormData:

public class LoginFormData {
  private String name;

  // getters and setters here
}

Update your controller to use it:

@GetMapping("/login")
public String showLogin(Model model) {
  model.addAttribute("spieler", new LoginFormData());
  return "login"; // assuming your template is called `login.html`
}

@PostMapping("/login")
public String login (@ModelAttribute("spieler") LoginFormData formData){
    Spieler spieler = new Spieler(formData.getName());
    spielerRepository.save(spieler);
    return "redirect:/";
}

You can of course also use loginFormData as model attribute name, but then you need to update the HTML as well.

See Form handling with Thymeleaf for more details on this.

Upvotes: 1

Related Questions