Enum 을 활용한 라디오 버튼

알파로그·2023년 3월 25일
0

Spring MVC 활용 기술

목록 보기
23/42

🔗 요구사항 확인하기

✏️ Radio 버튼 구현

📍 Controller 계층

  • enum 에 선언한 data 들을 배열로 변경해 model 로 넘겨준다.
    @ModelAttribute("itemTypes")
    public ItemType[] itemTypes() {
        // enum 에 선언된 data 를 배열로 변환하는 로직
        return ItemType.values();
    }

📍 Web 계층 - add item

🔗 멀티 체크박스

  • 멀티 체크박스와 거희 비슷하다.
  • th:field
    • entity 의 필드
  • th:value
    • enum 의 배열
  • th:text
    • enum 에 설정했던 discription
<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"></label>
</div>

📍 소스 확인

  • 멀티 체크박스와 거의 비슷하다.
  • value 에 enum 값이 입력됬고,
    labal text 때문에 enum 의 discription 이 입력됬다.
  • radio 버튼은 히든 필드를 생성하지 않는다.
<div class="form-check form-check-inline">
    <input type="radio"
           value="BOOK"
           class="form-check-input" 
           id="itemType1" 
           name="itemType">
    <label for="itemType1"
           class="form-check-label">도서</label>
</div>

<div class="form-check form-check-inline">
    <input type="radio" value="FOOD" class="form-check-input" id="itemType2" name="itemType">
    <label for="itemType2"
           class="form-check-label">음식</label>
</div>

<div class="form-check form-check-inline">
    <input type="radio" value="ETC" class="form-check-input" id="itemType3" name="itemType">
    <label for="itemType3"
           class="form-check-label">기타</label>
</div>

📍 log 확인

  • Controller 에 로그를 추가했다.
log.info("item.itemType = {}", item.getItemType());
  • 체크한 버튼이 참조탁입으로 잘 전달된다.
INFO 46066 --- [nio-8080-exec-8] h.i.web.form.FormItemController          
		: item.itemType = FOOD
  • 히든 필드가 없기 때문에 체크를 안하면 null 이 전달된다.
    • radio box 는 수정시 선택을 안할 수 없기 때문에 히든 필드가 필요없다.
INFO 46066 --- [nio-8080-exec-8] h.i.web.form.FormItemController          
		: item.itemType = null

✏️ 수정, 조회 추가

  • item 은 조회기 때문에 disabled 속성이 추가되었다.
<!-- edit -->
<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"></label>
</div>

<!-- item -->
<div th:each="type : ${itemTypes}" class="form-check form-check-inline">
    <input type="radio"
           th:field="${item.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>
profile
잘못된 내용 PR 환영

0개의 댓글