Reputation: 824
I have a variable inside a form in thymleaf, The variable is a date that has to be embedded to a method in controller that will display the data for the particular date. My problem is when the variable is selected and submitted i get a weird link in my url like this localhost:8080/masomo/somo/?date=11-03-2021&date=date without any response to that particular page. What am I doing wrong on submitting the variable.
Here is the form in thymleaf in masomo.html
<form th:action="@{/masomo/somo/}">
<select id="date" name="date" required="true">
<option value="none" selected disabled hidden >
Select a Date
</option>
<th:block th:each="somoChagua : ${masomoChagua}">
<option th:each="date : ${somoChagua.date}" th:value="${date}" th:text="${date}" ></option>
</th:block>
</select>
<button type="submit" th:name="date" th:value="date" ><i class="fa fa-search"></i> </button>
</form>
Here is how I set the method in controller to receive the variable
@Autowired
private MisaleRepository misaleRepository;
@RequestMapping(value = "/masomo/somo/{date}", method=RequestMethod.GET )
public String chaguaSomo(@RequestParam(value = "date", required = true) String date, Model model ){
List<Misale> masomo = misaleRepository.getSomoBytarehe(date);
model.addAttribute("masomoYote", masomo);
return "masomo";
}
Here is my Repository
public interface MisaleRepository extends JpaRepository <Misale, String> {
@Query(value ="SELECT * FROM misale WHERE misale.date = ?1 " , nativeQuery = true)
public List<Misale> getSomoBytarehe(String date);
}
Upvotes: 2
Views: 375
Reputation: 824
I had to change my form like below
<form th:action="@{'/masomo/somo/' + ${date}}">
And I changed the button to
<button type="submit"><i class="fa fa-search"></i> </button>
Also I changed the method in controller to
@GetMapping("/masomo/somo/{date}")
public String chaguaSomo(@RequestParam(value = "date",required = true) String date, Model model ){......}
After the above changes I could now pass the data from the form inside a block th:each to the controller
Upvotes: 0
Reputation: 89
Remove th:name
and th:value
in the submit button line
<button type="submit" ><i class="fa fa-search"></i> </button>
The date value is passed from view to controller as request param but the controller is receiving it as path variable.
@RequestMapping(value = "/masomo/somo/", method=RequestMethod.GET )
public String chaguaSomo(@RequestParam(value = "date", required = true) String date, Model model )
Upvotes: 1