get enum class values to dropdown list - java

I have an enum class and I want to get values of enum class into the dropdown list. The following code shows how I tried to do it. (I just add enum values as values of options in select). but I want to get data from enum class as the dropdown item.
-Enum class
public enum Status implements BaseEnum {
PENDING(0, "PENDING"), PROCESS(1, "PROCESS"), REJECT(2, "REJECT"));
private int code;
private String name;
private Status(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public String getName() {
return name;
}
private static final Map<Integer, Status> LOOKUP = new HashMap<Integer, Status>();
static {
for (Status status: EnumSet.allOf(Status.class)) {
LOOKUP.put(status.getCode(), status);
}
}
public static Status fromCode(int code) {
return LOOKUP.get(code);
}
}
-Dropdown list
<select class="form-control" id="status">
<option value="${statusDTO.status}">${statusDTO.status}</option>
<option value="PENDING">PENDING</option>
<option value="PROCESS">PROCESS</option>
<option value="REJECT">REJECT</option>
</select>

If you want to show all values in your Status enum in dropdown list, you can do as follows:
<select id="status" name="status">
<option th:each="status : ${T(com.stackoverflow.enums.Status).values()}"
th:value="${status}" th:text="${status}"></option>
</select>
You can do as follows to show a different value:
<select id="status" name="status">
<option th:each="status : ${T(com.stackoverflow.enums.Status).values()}"
th:value="${status}" th:text="${status.name}"></option>
</select>
If you want to highlight your choice, you can use if statement:
<select id="status" name="status">
<option
th:each="status : ${T(com.stackoverflow.enums.Status).values()}"
th:value="${status}" th:text="${status.name}"
th:selected="${status == statusDTO.status}"></option>
</select>
You can reproduce these examples, you can review this article for different enum scenarios or this article for different select scenarios.

Related

Getting values from enum in thymeleaf

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 class="form-group">
<label for="roomType">Rooms</label>
<select class="form-select selectpicker show-tick" 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
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 class="form-group">
<label for="rooms">Rooms</label>
<select class="form-select selectpicker show-tick" 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

Generate html select option from database in spring mvc app with thymeleaf

In spring based web app using hibernate I have a lists.html file where are select options codes reused in many views, now options will be transferred to database and my task is to populate those lists from db. This code will be rarely updated.This is example of list and its usage.
lists.html
<select th:fragment="typeList">
<option selected value=""></option>
<option th:value="|1|" th:text="|Type #1|"></option>
<option th:value="|2|" th:text="|Type #2|"></option>
<option th:value="|3|" th:text="|Type #3|"></option>
<option th:value="|4|" th:text="|Type #4|"></option>
</select>
usage
<li>
<label for="type" th:text="#{type.label}">type</label>
<select th:field="*{type}" th:include="html/fragments/lists :: typeList"></select>
</li>
What is the best method to build this lists.html from database dictionary?
My DTO
#Entity
#Table(name = "TableName")
public class Test {
#Id
private String Code;
private String Name;
private int price;
public Test() {}
public Test(String Code, String Name, int price) {
this.Code = Code;
this.Name = Name;
this.price = price;
}
public String getCode() {
return Code;
}
public String getName() {
return Name;
}
public int getPrice() {
return price;
}
}
View
List<Test> test = new ArrayList<>();
model.addAttribute("test", test);
List<Test> tests = testRepository.findAll();
model.addAttribute("tests", tests);
HTML
<select class="form-control" id="Order" name="Order">
<option value="">Select Test Order</option>
<option th:each="test : ${tests}"
th:value="${test.Code}"
th:text="${test.Code}+' : '+${test.Name}"></option>
</select>
</div>
Reference
Reference link

How to Convert enum field to a String in a spring boot application saving to a mysql varchar columnm

I have an enum class with user types admin, client and supplier. I have annotated my userType attribute in the User Model class with #Enumerated(EnumType.STRING) . However, i have an error of type mismatch when i run my code.
I'm using spring boot and mysql database with varchar for the Enum usertype field. my below code has more in details.
My enum class
UserType.java
public enum UserType {
CLIENT ("Client"),
SUPPLIER ("Supplier"),
ADMIN ("Admin");
private final String type;
UserType (String userType){
this.type = userType;
}
public String getType() {
return this.type;
}
}
User.java
code snippet for the UserType utype.
#Entity
public class User{
#Enumerated(EnumType.STRING)
#Column (name = "user_type", nullable = false)
private UserType utype;
#Enumerated(EnumType.STRING)
public UserType getUtype() {
return utype;
}
#Enumerated(EnumType.STRING)
public void setUtype(UserType utype) {
this.utype = utype;
}
}
Controller
#GetMapping(value="/newUser")
public String registrationForm(Model model){
model.addAttribute("user", new User());
model.addAttribute("UserTypes", UserType.values());
return "register";
}
#PostMapping(value="/registerUser")
public String registerUser(#ModelAttribute(value = "user") User user){
userService.save(user);
return "pages/login";
}
ThymeLeaf View File
register.html
<select th:field="*{utype}" >
<option th:each="usertype : ${UserTypes}"
th:text="${usertype.type}"
th:value="utype">
</option>
</select>
I expected the input for the utype to be converted to string but i'm having the following error.
Field error in object 'user' on field 'utype': rejected value [utype]; codes [typeMismatch.user.utype,typeMismatch.utype,typeMismatch.com.grocery.demo.Model.UserType,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.utype,utype]; arguments []; default message [utype]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.grocery.demo.Model.UserType' for property 'utype'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [#javax.persistence.Enumerated #javax.persistence.Column com.grocery.demo.Model.UserType] for value 'utype'; nested exception is java.lang.IllegalArgumentException: No enum constant com.grocery.demo.Model.UserType.utype]]
mysql is configured using application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/FredSystems
spring.datasource.username=root
spring.datasource.password=fred#2017
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.messages.basename=validation
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Do it as simple as below :
Controller
#GetMapping(value="/newUser")
public String registrationForm(Model model){
model.addAttribute("user", new User());
model.addAttribute("UserTypes",Arrays.asList(UserType.values()));
return "register";
}
In your thymeleaf:
<select th:field="*{utype}" >
<option th:each="usertype : ${UserTypes}"
th:text="${usertype}"
th:value="${usertype}">
</option>
</select>
If JSP:
<select id="editState"class="form-control">
<c:forEach items="${UserTypes}" var="ut" varStatus="loop">
<option value="${ut}">${ut}</option>
</c:forEach>
</select>
in your enum add this method
public static UserType getByName(String name) {
for (UserType type : UserType.values()) {
if (type.getName().equals(name)) {
return type;
}
}
return null;
}
in your thymeleaf
<select th:field="*{utype}" >
<option th:each="usertype : ${UserTypes}"
th:text="${usertype.type}"
th:value="${utype.type}">
</option>
</select>
and then from backend try to use getByName method to parse your HTML input.
Firstly, try to have a field in enum which exactly matches your ENUM value. This will ease in fetching any enum
e.g.
public enum UserType {
CLIENT ("CLIENT","Client"),
SUPPLIER ("SUPPLIER","Supplier"),
ADMIN ("ADMIN","Admin");
private final String type;
private final String name;
UserType (String name, String userType){
this.name=name;
this.type = userType;
}
public String getType() {
return this.type;
}
}
For your purpose you can try overriding toString() method according to your values.
The problem is in your register.html:
<select th:field="*{utype}" >
<option th:each="usertype : ${UserTypes}"
th:text="${usertype.type}"
th:value="utype">
</option>
</select>
In the th:value tag you use an incorrect reference to the utype field. You should use a variable expression, where you declare what value you want to bind to your User object's utype field. So it should be something like this:
<select th:field="*{utype}" >
<option th:each="usertype : ${UserTypes}"
th:text="${usertype.type}"
th:value="${usertype}">
</option>
</select>
If it's still not working, please see my updated example project:
https://github.com/gybandi/spring-ui-demo

MVC: Value in dropdown menu doesn't set to selected value - remains 0

This is a spring Boot application that uses thymeleaf template manager. It has a simple form with dropdown menu. Options are populated from database, both their names (or ids) can be displayed correctly on form but after selecting option and submiting form value of given selected variable remains 0.
While I get the correct value of variable content, categoryId always has value 0 after submit (or null if I change it's type from int to Integer).
I'm guessing that model isn't correctly "linked" to jokeForm but I don't know how to link it correctly. I was following example 1. I hope someone can eassily spot the problem just by quickly looking at my code. Code breakes in method submitForm().
HTML form:
<html>
<body>
<form action="#" th:action="#{/new}" th:object="${jokeForm}" method="post">
<table>
<tr>
<td>Content:</td>
<td><input type="text" th:field="*{content}" /></td>
<td th:if="${#fields.hasErrors('content')}" th:errors="*{content}">Content Error</td>
</tr>
<tr>
<td>Category:</td>
<td>
<select name="categoryId" th:field="*{categoryId}">
<option value="0" th:each="category : ${categories}"
th:value="${category.id}"
th:utext="${category.name}"/>
<!-- <option th:each="category : *{categories}"
th:value="*{category.id}"
th:utext="*{category.name}"/> -->
</select>
</td>
<td th:if="${#fields.hasErrors('categoryId')}" th:errors="*{categoryId}">category Error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
</body>
</html>
Controller
#GetMapping("/new")
public String showForm( Model model) {
DEBUG("showForm");
JokeForm form = new JokeForm();
categories = categoryRepository.findAll();
DEBUG(categories.get(0).toString());
DEBUG(categories.get(1).toString());
//form.setCategories(categories); //not working
model.addAttribute("jokeForm", form);
model.addAttribute("categories",categories);
return "form";
}
#PostMapping("/new")
#ResponseBody
public String submitForm(#ModelAttribute JokeForm jokeForm) {
DEBUG("submitForm");
//String content = jokeForm.getContent();
DEBUG(jokeForm.getContent());
DEBUG(jokeForm.getCategoryId().toString());
Joke j = new Joke();
j.setContent(jokeForm.getContent());
//j.setCategoryId(jokeForm.getCategoryId());
//DEBUG(Integer.toString(jokeForm.getCategoryId()));
//CAUSES ERROR value of CategoryId is Integer -> null System.out.println(Integer.toString(jokeForm.getCategoryId()));
//PRODUCES ERROR value of CategorId is int (because no category matches) j.setCategory(categoryRepository.findById(jokeForm.getCategoryId().intValue()).get(0));
jokeRepository.save(j); //save
return "Saved";
}
JokeForm
public class JokeForm {
#NotEmpty(message = "content may not be empty")
private String content;
#NotEmpty(message = "category may not be empty")
private int categoryId; //int-> 0, Integer -> null
/*
#NotEmpty(message = "category may not be empty")
private Category category;
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
private List<Category> categories;
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
} */
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategory(Integer categoryId) {
this.categoryId = categoryId;
}
}
You set value="0" for all options.
<select> should be:
<select th:field="*{categoryId}">
<option th:each="category : ${categories}"
th:value="${category.id}"
th:utext="${category.name}"/>
<!-- <option th:each="category : *{categories}"
th:value="*{category.id}"
th:utext="*{category.name}"/> -->
</select>
Edit:
and add (setter) setCategoryId() in JokeForm class

How to populate dropdown list with HashMap contained in an object, in Thymeleaf?

I have an object containing a HashMap and some other variables. That's the class defining it:
public class Student {
private String firstName;
private String lastName;
private String country;
public HashMap<String,String> countryOptions;
public Student()
{
// populate country options: used ISO country code
countryOptions = new HashMap<String, String>() {};
countryOptions.put("BR", "Brazil");
countryOptions.put("FR", "France");
countryOptions.put("DE", "Germany");
countryOptions.put("IN", "India");
}
// getters and setters...
}
I wanna send that object to the form as a Model, bind data from that form with that object and then display it on a confirmation page. Unfortunately, I have a problem with populating the dropdown list with entries from the HashMap.
My controller class:
#Controller
#RequestMapping("/student")
public class StudentController {
#RequestMapping("/showForm")
public String showForm(Model theModel)
{
Student theStudent = new Student();
theModel.addAttribute("student", theStudent);
theModel.addAttribute("country", theStudent.countryOptions);
return "student-form";
}
#RequestMapping("/save")
public String save(#ModelAttribute("student") Student theStudent)
{
return "student-confirmation";
}
}
student-form.html:
<body>
<form th:action="#{save}" th:object="${student}" method="post">
<input type="text" name="firstName" th:field="${student.firstName}"/>
<input type="text" name="lastName" th:field="${student.lastName}"/>
<select name="country" th:field="${student.country}">
<option th:each="country : ${student.countryOptions}" th:value="${student.countryOptions}" th:text="${student.countryOptions}"></option>
</select>
<input type="submit"/>
</form>
</body>
My result looks like this
What am I doing wrong?
Value and text attributes need to refer to country, otherwise thymeleaf will print countryOptions.toString()
<option th:each="country : ${student.countryOptions.entrySet()}"
th:value="${country.key}"
th:text="${country.value}">
</option>

Categories

Resources