체크박스를 이용해서 여러 개 항목을 체크해서 활용해보자.
이 기능은 Spring에서 제공해주는 기능으로 이 기능을 활용해 등록해두면 자동으로 컨트롤러의 모든 메서드의 Model에 추가해주는 기능이다.
사진처럼 해두면 모든 메서드에 model.addAttribute("regions", regions);
처리가 된 것과 동일한 기능이다.
<!-- 등록지역 -->
<div>
<div>등록 지역</div>
<div th:each="region : ${regions}" class="form-check form-check-inline">
<input type="checkbox" th:field="*{regions}" th:value="${region.key}" class="form-check-input">
<label th:for="${#ids.prev('regions')}" th:text="${region.value}" class="form-check-label">서울</label>
</div>
</div>
위 html을 보면 th:for="${#ids.prev('regions')}"
를 볼 수 있다.
th:for="${#ids.prev('regions')}"
는 앞에서 th:filed
로 만들어진 id 값을 자동으로 가져온다.
prev는 앞에서 사용된 id를 동일하게 가져온다. th:for="${#ids.prev('regions')}"
seq는 시퀀스 순서대로 새로운 id를 부여하여 처리한다.
th:for="${#ids.seq('regions')}"
next는 다음에 올 id를 동일하게 가져온다.
th:for="${#ids.next('regions')}"
수정폼에 들어가보면 아래와 같이 태그만 추가했는데, 실제로 실행해보면 저장된 값에만 체크박스가 되어있는 것을 확인할 수 있다. 어떻게 타임리프는 이를 알고 체크처리를 할 수 있는 걸까?
<!-- 등록지역 -->
<div>
<div>등록 지역</div>
<div th:each="region : ${regions}" class="form-check form-check-inline">
<input type="checkbox" th:field="*{regions}" th:value="${region.key}" class="form-check-input">
<label th:for="${#ids.prev('regions')}" th:text="${region.value}" class="form-check-label">서울</label>
</div>
</div>
타임리프는 th:field
로 들어오는 값과 th:value
로 들어오는 값을 보고 두 값이 같으면 체크가 된 것으로 판단하고 checked 처리를 해준다.
만약, th:value
로 들어오는 값은 있는데 th:field
로 들어오는 값이 없다면 체크가 되지 않은 걸로 간주하여 checked를 처리하지 않는다.
이 또한 자동으로 hidden 타입이 추가되어 처리하는 것을 알 수 있다.
라디오 버튼의 경우, hidden 태그가 생기는 것 외에는 위와 대부분 동일하게 처리가 된다.