Skip to content

Commit

Permalink
fix pagination 🐛
Browse files Browse the repository at this point in the history
  • Loading branch information
Petrovich-A committed Jul 10, 2023
1 parent 62cdd6a commit 942d767
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package by.petrovich.eshop.controllers;

import by.petrovich.eshop.entity.Product;
import by.petrovich.eshop.exceptions.UserNotFoundException;
import by.petrovich.eshop.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
Expand Down Expand Up @@ -37,8 +39,7 @@ public ModelAndView showCategoryPage(
@RequestParam("size") Optional<Integer> size) {
int currentPage = page.orElse(1);
int pageSize = size.orElse(NUMBER_ELEMENTS_ON_PAGE);
int id = categoryId.orElse(1);

int id = categoryId.orElse(categoryId.orElseThrow(() -> new BadCredentialsException("Bad credentials.")));
Page<Product> products = categoryService.findProductsByCategoryId(id,
PageRequest.of(currentPage - 1, pageSize));

Expand All @@ -52,6 +53,7 @@ public ModelAndView showCategoryPage(
.collect(Collectors.toList());
model.addAttribute("pageNumbers", pageNumbers);
model.addAttribute("currentPage", currentPage);
model.addAttribute("categoryId", categoryId);
}
return new ModelAndView(CATEGORY_PAGE, model);
}
Expand Down
6 changes: 3 additions & 3 deletions src/main/resources/templates/category.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,17 @@ <h2>Product Card</h2>
<nav>
<ul class="pagination">
<li th:class="${currentPage == 0} ? disabled : ''">
<a th:href="@{/category}">First</a>
<a th:href="@{/category(categoryId=${categoryId.get()})}">First</a>
</li>
<li th:if="${products.totalPages > 0}" class="page-link"
th:each="pageNumber : ${pageNumbers}">
<a th:href="@{/category(size=${products.size}, page=${pageNumber})}"
<a th:href="@{/category(size=${products.size}, page=${pageNumber}, categoryId=${categoryId.get()})}"
th:text=${pageNumber}
th:class="${pageNumber==products.number + 1} ? active" class="page-link">
</a>
</li>
<li th:class="${currentPage == pageNumbers[pageNumbers.size() - 1] ? 'disabled' : ''}">
<a th:href="@{/category(page=${pageNumbers[pageNumbers.size() - 1]})}">Last</a>
<a th:href="@{/category(page=${pageNumbers[pageNumbers.size() - 1]}, categoryId=${categoryId.get()})}">Last</a>
</li>
</ul>
</nav>
Expand Down

0 comments on commit 942d767

Please sign in to comment.