[thymeleaf] each안에 checkbox/radio btn/select 예제

유존돌돌이·2022년 3월 31일
0

thymleaf

목록 보기
1/1

Checkbox

@ModelAttribute("regions")
    public Map<String, String> regions() {
        Map<String, String> regions = new LinkedHashMap<>();
        regions.put("SEOUL","서울");
        regions.put("BUSAN","부산");
        regions.put("JEJU","제주");
        return regions;
    }
<form th:object="${item}">
...
<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" disabled>
	<label th:for="${#ids.prev('regions')}"
		   th:text="${region.value}" class="form-check-label">서울</label>
</div>

th:field="*{regions}" 에는 선택한 값들이 있고
th:value="${region.key} 에는 각 checkbox의 키값이 들어있음.
각 키값이 선택한 값들과 비교해서 있으면 해당 항목은 on 없다면 null처리 한다.
원래는 일일히 다 체크해줘야하는데 이걸 타임리프는 알아서 해준다

Radio Button

public enum ItemType {
    BOOK("도서"), FOOD("식품"), ETC("기타");
    private final String description;

    ItemType(String description) {
        this.description = description;
    }

    public String getDescription() {
        return description;
    }
}
<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" disabled>
		<label th:for="${#ids.prev('itemType')}" th:text="${type.description}" class="form-check-label">
        </label>
	</div>
</div>

Enum객체를 사용했음
1. ${type.description}을 사용하기 위해서는 getter필요
2. type.name()는 enum의 이름을 가져온다. (BOOK, FOOD, ETC)

Select

<div>
	<div>배송 방식</div>
		<select th:field="*{deliveryCode}" class="form-select">
		<option value="">==배송 방식 선택==</option>
		<option th:each="deliveryCode : ${deliveryCodes}" th:value="${deliveryCode.code}"
                th:text="${deliveryCode.displayName}">FAST</option>
	</select>
</div>

0개의 댓글