Home > Net >  thymeleaf replacing th:field to comply with th:selected
thymeleaf replacing th:field to comply with th:selected

Time:06-04

I appreciate your passing by my post. I have searched here in StackOverFlow and google as well to fix my following code:

My HTML code:

<form th:action="@{/surgerywaitinglist/saveToWaitinList}"
            th:object="${waitinglistDTO}" method="POST">
.
.
.    
<select name="departmentName"
                                        
            th:field="*{department.departmentName}"
            th:with="departmentName = ${waitinglistDTO.department.departmentName}"
             id="departmentJS">
        
        <option value="" th:selected="selected" 
              th:disabled="disabled">select option
        </option>
                                                
        <option th:each="department: ${departments}"
                th:value="${department.departmentName}"
                th:text="${department.departmentName}"> 
        </option>
        
    </select>
.
.
.
<input type="submit" value="Save"  />
</form>

form other posts like enter image description here

CodePudding user response:

I don't see why you would add the selected to the blank option, the first option is always selected if your model object has nothing set and if it does normal behaviour would be to have that item selected, which th:field should resolve.

In case you want the select to always start at the default option, even if the model has another value or want to set it some other way. you can set th:id="*{department.departmentName}" and th:name="*{department.departmentName}" and than manualy handle th:selected.

As a side note theres no need to use the th version th:selected="selected" if using static values just selected or selected="selected would sufice in that case

CodePudding user response:

you can do like this:

<select name="departmentName" th:field="*{department.departmentName}" th:with="departmentName = ${waitinglistDTO.department.departmentName}"  id="departmentJS">
    <option selected="selected" disabled="disabled">select option</option>
    <option th:each="department : ${departments}" th:value="${department.departmentName}" th:text="${department.departmentName}"></option>
</select>

this worked for me.

  • Related