개발

thymeleaf에서 th:field와 th:selected 중복사용

yjs3819 2021. 8. 3. 17:58
728x90

타임리프에서 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

728x90