Thymeleafでプルダウンの初期値を設定

Thymeleafでプルダウンの初期値を設定

Thymeleafでプルダウンの初期値を設定する方法を以下に示します。

まず、コントローラーで初期値を設定します。
次に、Thymeleafテンプレートでプルダウンメニューを作成し、初期値を選択状態にします。

コントローラー

@Controller
public class SampleController {

  @GetMapping("/form")
  public String showForm(Model model) {
    List<String> options = Arrays.asList("Option1", "Option2", "Option3");
    model.addAttribute("options", options);
    model.addAttribute("selectedOption", "Option2"); // 初期値を設定
    return "form";
  }
}

Thymeleafテンプレート (form.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>プルダウンの初期値設定</title>
</head>
<body>
  <form action="#" th:action="@{/submit}" method="post">
    <label for="options">選択肢:</label>
    <select id="options" name="options" th:field="*{selectedOption}">
      <option th:each="option : ${options}"
              th:value="${option}"
              th:text="${option}"
              th:selected="${option == selectedOption}"> <!-- 初期値の設定 -->
      </option>
    </select>
    <button type="submit">送信</button>
  </form>
</body>
</html>

上記の例では、selectedOptionに"Option2"が設定されています。
この値を基に、Thymeleafテンプレートでプルダウンの初期値を設定しています。
th:selected属性を使用して、optionがselectedOptionと一致する場合にそのオプションを選択状態にします。