I'm using enum for select options in thymeleaf and I can't see them or insert them in the database. There is nothing in the dropdown list.
<div >
<label for="roomType">Rooms</label>
<select th:field="*{property.roomType}" id="rooms">
<option value="">Nothing selected</option>
<option th:each="property.roomType : ${T(com.realestate.petfriendly.entity.RoomType).values()}"
th:value="${property.roomType}"
th:text="${property.roomType}">
</option>
</select>
</div>
class
@Enumerated(EnumType.STRING)
@Column(name = "RoomType")
private RoomType roomType;
and enum
public enum RoomType {
GARSONJERA("garsonjera"), JEDNOIPOSOBAN("jednoiposoban"), DVOSOBAN("dvosoban"),
DVOIPOSOBAN("dvoiposoban"), TROSOBAN("trosoban"), TROIPOSOBAN("troiposoban"),
CERVOROSOBAN("cetvorosoban"), CETVOROIPOSOBAN("cetvoroiposoban"), VISESOBAN("visesoban");
private String roomType;
private RoomType(String roomType) {
this.roomType = roomType;
}
public String getRoomType() {
return this.roomType;
}
}
I'm not sure why it doesn't show me anything
CodePudding user response:
that is available for me.
class
@Setter
@Getter
public class Demo {
private RoomType roomType;
}
enum
public enum RoomType {
GARSONJERA("garsonjera"), JEDNOIPOSOBAN("jednoiposoban"), DVOSOBAN("dvosoban"),
DVOIPOSOBAN("dvoiposoban"), TROSOBAN("trosoban"), TROIPOSOBAN("troiposoban"),
CERVOROSOBAN("cetvorosoban"), CETVOROIPOSOBAN("cetvoroiposoban"), VISESOBAN("visesoban");
private final String roomType;
private RoomType(String roomType) {
this.roomType = roomType;
}
public String getRoomType() {
return this.roomType;
}
}
controller:
@Controller
@RequestMapping( "test")
public class TestController {
@GetMapping("demo")
public String demo(Model model){
Demo demo = new Demo();
demo.setRoomType(RoomType.CERVOROSOBAN);
model.addAttribute(demo);
return "test/demo";
}
}
HTML:
<div >
<label for="rooms">Rooms</label>
<select th:field="*{demo.roomType}" id="rooms">
<option value="">Nothing selected</option>
<option th:each="value : ${T(com.bluray.boot.business.test.RoomType).values()}"
th:value="${value}"
th:text="${value}">
</option>
</select>
</div>
I use spring-boot 2.3.6.release
CodePudding user response:
The problem is here
<option th:each="!!!!property.roomType!!!!<---- : ${T(com.realestate.petfriendly.entity.RoomType).values()}"
th:value="${property.roomType}"
th:text="${property.roomType}">
</option>
While it should be
<option th:each="property : ${T(com.realestate.petfriendly.entity.RoomType).values()}"
th:value="${property.roomType}"
th:text="${property.roomType}">
</option>
You iterate through the list and you take each element. You don't access nested elements of that property during each
iteration. You already do this later when you access the property by th:value="${property.roomType}"