The question here is kind of divided into 2 parts. First part is more of displaying the enum on the UI and the second part deals with handling the selected value not in the enum list on the service side.
To begin with.I have an Enum class Gender defined as below.
public enum Gender {
Male("M"),
Female("F");
private String name;
private Gender(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The above enum class is referenced in the User Object as below.
public class UserBO {
private Gender gender;
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
//other getters and setters
}
In the controller I return this userObject and the dropdown lists for the genders by doing this.
@Controller
public class UserController {
@Autowired
private IUserService userServiceImpl;
@RequestMapping(value = "/user/{userId}/official", method = RequestMethod.GET)
public String getUserOfficialInfo(@PathVariable("userId") Integer userId, Model model) throws ServiceBusinessException {
UserBO userBO = userServiceImpl.findUserByUserId(userId);
model.addAttribute("user", userBO);
model.addAttribute("userId", userId);
model.addAttribute("genders", EnumSet.allOf(Gender.class));
return "official";
}
Now gender is not a required field in the user object, so it may happen that for some users this field is not populated at all. How should I be handling this condition on the UI. I am using thymeleaf on UI.
the code which I have tried on thymeleaf is this
<label class="control-label col-xs-2">Marital Status</label>
<div class="col-xs-2">
<select id="maritalStatus" name="maritalStatus">
<option th:each="status : ${maritalStatuses}"
th:value="${status}"
th:text="${status}"
th:selected="${user.maritalStatus == null} ? 'Please select a Value' : ${status.equals(user.maritalStatus.name)}">
</option>
</select>
</div>
Can someone please advice on how can i handle this ?
Also coming to the second part of the question, say the user does not select any gender on form submit since its not a required field. How should that be handled on the UI, so that service does not throw an exception if it receives a gender not in the gender enum list.
Easiest is to use
th:object
in the form as shown below: