스프링/스프링 MVC 패턴
라디오 버튼 (상품 종류 : 도서, 식품, 기타)
chanhee01
2023. 2. 19. 15:19
ItemType enum 생성
package hello.itemservice.domain.item;
public enum ItemType {
BOOK("도서"), FOOD("음식"), ETC("기타");
private final String description;
ItemType(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
enum을 이용한 코드를 만들 예정이니 enum을 생성해주었다.
@ModelAttribute("itemTypes")
public ItemType[] itemTypes() {
ItemType[] values = ItemType.values();
return values;
}
ModelAttribute 애노테이션을 이용해서 values를 모델에 넘길 수 있도록 했다. enum의 모든 itemTypes를 반환해준다.
addForm.html
<!-- radio button -->
<div>
<div>상품 종류</div>
<div th:each="type : ${itemTypes}" class="form-check form-check-inline">
<input type="radio" th:field="*{itemType}" th:value="${type.name()}"class="form-check-input">
<label th:for="${#ids.prev('itemType')}" th:text="${type.description}" class="form-check-label">
BOOK
</label>
</div>
</div>
addForm.html에 해당 코드를 추가해준다. 이전에 했던 코드들과 비슷한 내용이니 굳이 추가 설명을 안해도 되는데 한 가이 차이점은 라디오 타입 이라는 것이다.
보이는 것과 같이 상품 종류 중에 하나밖에 선택을 하지 못한다.
상품 상세 정보와 상품 수정 폼에도 위와 같은 코드를 넣어주면 된다
<input type="radio" th:field="${item.itemType}" th:value="${type.name()}"class="form-check-input" disabled>
(상품 상세 정보는 수정이 안되니 뒤에 disabled를 붙여주자)
라디오 버튼은 체크 박스와 다르게 히든 필드가 없다. 한 번 체크하면 체크한 것을 뺄 수 없고 다른 항목을 선택해야지만 뺄 수 있다.