This question already has an answer here:
- How do I get the selected value from a drop-down menu with Thymeleaf? 1 answer
I have a form where the user is creating a new exam and in the form the user selects a subject from a drop down menu. This drop down contains strings of subjects not actual subject objects. In my program there are actual subject objects which have a one to many relationship with exam.
How do I find what value the user selected? I want to add it to the model so that I can create an exam object and add it to the database.
Once the subject string that the user selected is added to the model how do I find the value the user selected? As I want to set what they selected to equal subject Name and then search the subject repository for a subject with the same name so that the exam can be added to that subject.
Hopefully my code will make this a bit more clear.
I am getting this error. Neither Binding Result nor plain target object for bean name subject available as request attribute.
This the code form my Controller
@GetMapping("/addexam")
public String showExamForm(Model model) {
// Here I am finding the subjects that belong to the current user
//and adding them as strings to an arraylist.
//I populate the dropdown with strings fromthis arraylist.
Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
String email = loggedInUser.getName();
User user = userRepository.findByEmailAddress(email);
ArrayList<String> subjects = new ArrayList<String>();
for(Subject sub:user.getSubject())
{
subjects.add(sub.getSubjectName());
}
model.addAttribute("subjects", subjects);
return "addExam";
}
@PostMapping("/addexam")
public String addNewExam(@ModelAttribute("exam") @Valid @RequestBody Exam
exam,UserRegistrationDto userDto, BindingResult result, Model model) {
examRepository.save(exam);
model.addAttribute("examTitle", exam.getExamTitle());
model.addAttribute("examGradeWorth", exam.getExamGradeWorth());
model.addAttribute("subject", exam.getSubject());
//I want to find the user selected value and set it to equal
//subjectname:
String subjectName =;
//Here I will search the subjectRepository for the subjectName and set subject to equal the subject that was found.
Subject subject = subjectRepository.findBySubjectName(subjectName);
//then exam will be added to that subject as subject has a one to many relationship with exam.
subject.addExam(exam);
subjectRepository.save(subject);
return "userProfile1";
}
}
This is the html.
<form action="#" th:action="@{/addExam}" th:object="${exam}"
method="post">
<div th:object="${subject}">
<select th:field="*{subject}" class="form-control" id="subject"
name= "subject">
<option value="">Select subject</option>
<option
th:each="Subject : ${subjects}"
th:value="${Subject}"
th:text="${Subject}"></option>
</div>
<div>
<table>
<tr>
<td><input type="text" th:field="*{examTitle}" /></td>
</tr>
<tr>
<td> Exam grade worth </td>
<td><input th:field="*{examGradeWorth}" /></td>
</tr>