プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

Thymeleaf ラジオボタンの作成と初期化

■完成画面

 
 


■ラジオボタンの作成方法

コントローラークラスにラジオボタンの「フィールド」と「初期化メソッド」を作成
モデルオブジェクトにセットし、画面に渡す
 

【記述例】

@Controller
public class CustomerController {
    //ポイント1
    private Map<String, String> radioGender;

    //ポイント2
    private Map<String, String> initRadioGender() {
        Map<String, String> radio = new LinkedHashMap<>();
        radio.put("0", "男性");
        radio.put("1", "女性");
        return radio;
    }

    @GetMapping("create")
    String create(CustomerForm customerForm, Model model) {
        //ポイント3
        radioGender = initRadioGender();
        model.addAttribute("radioGender", radioGender);

        //ポイント4
        customerForm.setGender("0");
        model.addAttribute("customerForm", customerForm);
        return "create";
    }
}

 

【ポイント】

1.ラジオボタンのマップを作成
 
2.初期化メソッドを作成し、ラジオボタンを格納
 
3.2のメソッドの戻り値を1で作成したマップに格納し、addAttribute()メソッドでモデルオブジェクトにセット
 
4.ラジオボタンの初期値をセット
customerForm.setGender()メソッドで初期値を「男性」としている
 
 


■Thymeleaf

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" th:href="@{/webjars/bootstrap/4.3.1/css/bootstrap.min.css}">
<title>顧客登録</title>
</head>
<body>
    <div class="container">
        <h1 class="my-3">顧客登録</h1>
        <hr class="mb-5">
        <form th:action="@{/create}" th:object="${customerForm}" method="post">
            <table class="table table-bordered table-striped table-hover col-md-6">
                <tr class="form-group">
                    <th class="align-middle">名前</th>
                    <td><input type="text" class="form-control" th:field="*{name}"></td>
                </tr>
                <tr class="form-group">
                    <th class="align-middle">メールアドレス</th>
                    <td><input type="text" class="form-control" th:field="*{email}"></td>
                </tr>
                <tr class="form-group">
                    <th class="align-middle">性別</th>
                    <td>
                        <!-- ポイント1 -->
                        <div th:each="item : ${radioGender}" class="form-check-inline">
                            <!-- ポイント2 -->
                            <input type="radio"  class="form-check-input" th:text="${item.value}" th:value="${item.key}" th:field="*{gender}">
                        </div>
                    </td>
                </tr>
            </table>
            <input type="submit" class="btn btn-primary" value="登録">
        </form>
    </div>
    <script th:src="@{/webjars/jquery/3.4.1/jquery.min.js}"></script>
    <script th:src="@{/webjars/bootstrap/4.3.1/js/bootstrap.min.js}"></script>
</body>
</html>

 

【ポイント】

1.ラジオボタン横並び
「form-check-inline」でラジオボタンを横並びにする
 
2.ラジオボタン
ラジオボタンには「form-check-input」を記述する