타임리프에서 th:field와 th:selected를 중복으로 사용하면 둘중 하나가 적용이 되질않는다.
상황
th:field로 th:object에서 감싼 필드를 사용하고있었는데, th:selected가 계속 되질 않는 것이다.. 찾아보니 th:field와 th:selected는 동시에 적용이 되지 않는다는것을 알게되었다.
<label class="form-label"> 카테고리
<select class="form-select" th:field="*{category}">
<option th:value="null" th:selected="${item.category == null}">기타</option>
<option th:each="categoryOne: ${categories}" th:value="${categoryOne.id}" th:text="${categoryOne.name}"
th:selected="${item.category != null && item.category.id == categoryOne.id}">category name</option>
</select>
</label>
해결
th:field는 name, id 속성과 필드가 매핑되어 값이 적절하게 들어간다.
그냥 직접 풀어서 사용하여 th:field를 사용하지않고 th:selected만 사용하여 해결
<label class="form-label"> 카테고리
<select class="form-select" name="category" id="category">
<option th:value="null" th:selected="${item.category == null}">기타</option>
<option th:each="categoryOne: ${categories}" th:value="${categoryOne.id}" th:text="${categoryOne.name}"
th:selected="${item.category != null && item.category.id == categoryOne.id}">category name</option>
</select>
</label>
뭐가문젠지 모르겠어서 해결하는데 꽤 걸렸다..
https://stackoverflow.com/questions/32206849/spring-mvc-thymeleaf-thselected-not-working
'개발' 카테고리의 다른 글
맵드 타입(Mapped Type) (0) | 2022.06.13 |
---|---|
eslint, prettier 그리고 github action (0) | 2021.11.14 |
ec2에 mysql server를 이용해서 spring boot서버를 배포해보자. (1) | 2021.09.16 |
spring security를 살짝 적용해보자! (0) | 2021.07.30 |
springboot + jpa + mysql (0) | 2021.07.19 |