A visual explanation of my code
I built a Spring Boot Application and from the search bar, I'm trying to search based on SKU and Make separately by choosing the dropdown button as shown in the picture. By default the code is searching for SKUs with no issues but I would love to switch back and forth from SKU and Make and change my thymeleaf action path from my form.
Repository Class (It consists two queries to search based on SKU and Make):
@Repository
public interface ExcelFileRepository extends JpaRepository<ExcelFile, Integer> {
@Query(value = "select * from excel_file e where e.sku like %:sku%", nativeQuery=true)
List<ExcelFile> findBySKU(@Param("sku") String keyword);
@Query(value = "select * from excel_file e where e.make like %:make%", nativeQuery=true)
List<ExcelFile> findByMake(@Param("make") String keyword);
}
Service class:
public List<ExcelFile> findBySKU(String keyword)
{
return efRepository.findBySKU(keyword);
}
public List<ExcelFile> findByMake(String keyword)
{
return efRepository.findByMake(keyword);
}
Controller Class:
@Controller
public class DBController
{
@Autowired
private ExcelFileService efService;
@GetMapping(path={"/dbs","/searchSKU"})
public String findAll(ExcelFile e,Model model, String keyword) {
List<ExcelFile> dbList;
if(keyword == null)
{
dbList = efService.getAllData();
}else {
dbList = efService.findBySKU(keyword);
}
model.addAttribute("dbs", dbList);
return "Db";
}
@GetMapping(path="/searchMake")
public String searchMake(ExcelFile e,Model model, String keyword) {
List<ExcelFile> dbList;
if(keyword == null)
{
dbList = efService.getAllData();
}else {
dbList = efService.findByMake(keyword);
}
model.addAttribute("dbs", dbList);
return "Db";
... more code...
}
HTML file
<form name="searchForm" id="searchForm" th:action="@{/searchSKU}">
<div class="row">
<div class="col-sm-12 col-md-5">
<label>Search by </label>
<select name="searchTypes">
<option>-SELECT-</option>
<option th:value="searchSKU" id="searchSKU">SKU</option>
<option th:value="searchMake" id="searchMake">MAKE</option>
</select>
</div>
<div class="col-sm-12 col-md-4">
<input type="search" class="form-control form-control-sm" name="keyword"
th:value="${keyword}">
</div>
<div class="col-sm-12 col-md-2">
<input type="submit" class="btn-success">
</div>
</div>
</form>
<script th:inline="javascript">
var makeAction = /*[[@{/searchMake}]]*/ '/searchMake';
var skuAction = /*[[@{/searchSKU}]]*/ '/searchSKU';
$("#searchTypes").change(function () {
if ($(this).val() == "searchMake") {
$("#searchForm").attr("action", makeAction);
}else if ($(this).val() == "searchSKU") {
$("#searchForm").attr("action", skuAction);
}
});
</script>
Anyone who has experience with script inlining know how to deal with thymeleaf and changing th:action path?