Thymeleafを使用してチェックボックスなどのデフォルト値を送信する

checkboxや複数選択のselectで1つも選択されなかった場合に、Formのプロパティにデフォルト値を設定する方法について説明します。

Tip

正しい実装を行わないと、未選択状態ではFormのプロパティがnullとなります。 このため、サーバサイドではnull判定が必要になりプログラムが煩雑になります。

以下のサンプルコードの動作確認環境については、 動作確認環境と依存ライブラリについて を参照してください。

デフォルト値の設定方法

checkboxやselectでデフォルト値を送信するためには、Thymeleafのth:objectとth:fieldを使用します。 この2つを使用するだけで、checkboxやselectに対応するFormのプロパティにはデフォルト値が設定されます。

詳細は、以下の公式ドキュメントのcheckboxの部分などを参照してください。

警告

デフォルト値を受け取れる型は限定されています。 Formのプロパティを誤った型で定義しているとデフォルト値が設定されず、プロパティの値はnullのままとなるため注意してください。

対応している型については、以下のJavadocを参照してください。

実装例

Form

上で説明したように、Formのプロパティの型を適切な型で宣言します。

private Boolean checkbox;

private List<Options> checkboxes;

private List<Options> selectOptions;
View

上で説明したように、th:objectとth:fieldを使用して入力欄(checkboxやselect)を作成します。

<form th:action="@{/default}" th:object="${form}" method="post">
  <div>
    <input type="checkbox" th:field="*{checkbox}" id="checkbox"/>
    <label for="checkbox">単一チェックボックス</label>
  </div>
  <div>
    複数チェックボックス<br/>

    <!--/*@thymesVar id="type" type="keel.thymeleaf.DefaultValueSampleController.Options"*/-->
    <th:block th:each="type: ${T(keel.thymeleaf.DefaultValueSampleController.Options).values()}">
      <input type="checkbox" th:field="*{checkboxes}" th:value="${type.name()}" th:id="${type.name()}">
      <label th:for="${type.name()}" th:text="${type.name()}"></label>
    </th:block>
  </div>
  <div>
    複数選択セレクトボックス<br/>
    <select th:field="*{selectOptions}" multiple>
      <!--/*@thymesVar id="type" type="keel.thymeleaf.DefaultValueSampleController.Options"*/-->
      <option th:each="type: ${T(keel.thymeleaf.DefaultValueSampleController.Options).values()}"
              th:value="${type.name()}"
              th:text="${type.name()}">
    </select>
  </div>
  <button type="submit">送信</button>
</form>

サンプル全体は template-engine-thymeleaf-sample を参照してください。