Get selected value from a Thymeleaf drop down list

Viewed 415

i have a drop down list and the client must select a value then it will be persist in mysql db okay i did that but i want when the client select a value i get that value and i do an if statement exemple :

if selected value is : CIN then compte.setcomptenumber(25364138); like that

this my controller :

@RequestMapping(value="/addClient")
public String addClient (Model model) {
    Client client= new Client();
    Compte compte = new Compte();
    Agence agence = new Agence();
    //Carte carte = new Carte();
    model.addAttribute("client",client);
    List<String> typepieceList = Arrays.asList("CIN","Passeport");
    




    return "client";

} 

my html :

<div class="p-col-12">
<label class="p1">Choisir Type de la pièce d'identité
</label> <br> <select th:field="*{typepieceClient}"
                                    class="form-control" required="required">
                                    <option value=""></option>
                                    <option th:each="p: ${typepieceList}" th:value="${p}"
                                        th:text="${p}" class="p1"></option>
                                </select>
                            </div>
2 Answers

Your rest controller should accept the values passed from the form.

You can either pass the drop down value as a path param using @PathVariable annotation or

If you want to submit the entire form to the Rest Controller you have to configure it to use @ModelAttribute

ex:

@RequestMapping(value="/addClient")
public String addClient(@ModelAttribute Model model) 

What you are doing here is, you defined an end point /addClient and when you call this endpoint from the browser:

  1. You are creating a Model called Client [ model.addAttribute("client",client);]
  2. The calling the html file with this model and returning to the browser.

This is only one half of the solution. In order to be able to accept the values from the dropdown, you need another endpoint where you can submit this form.

  1. For this new endpoint you need to accept a Model from the html using the declaration like @RequestMapping(value="/addClient") public String addClient(@ModelAttribute Model model)

  2. And then from the html, you should be able to use a form tag and submit the form to this end point.

I would suggest please check this article https://spring.io/guides/gs/handling-form-submission/

Related