Chciałem się przetestować i napisałem taki oto teoretyczniedobry kod jak dla mnie do twrozenia paginacji na stronie, próbowałem robić nawet dokumentację na górze ale mój angielski pozostawia bardzo wiele do życzenia, prosiłbym o ocenę i wypowiedzi na ten temat, wiem do symfony są bundle z paginacją jednak udostępniam to w celu oceny własnych umiejętności ;)
public function articlesAction( $numPage = 0 )
{
////////////////////CONFIGURATION/////////////////////////////
// @Param $numPage is getting from route default is set to 0
// You must set this parametr in Your route with requirements
// like this:requirements={"numPage": "\d+"}
// Full route like this:
// @Route("/articles/{numPage}",
// name="articles_list",
// requirements={
// "numPage": "\d+"
// })
$articlesPerPage = 15;//Num of articles display on single page min 1
$repository = "AppBundle:Articles";//Database Table like "<NameBundle>:<Entity>"
$orderBy = "dateinsert";//Order by Column prefer id or Date of insert
$sortBy = "DESC";//Sort results put ASC or DESC prefer DESC for display first newest records
$twigTemplatePath = "articles.html.twig";//path to the template like: "articles.html.twig"
//////////////////END CONFIGURATION///////////////////////////
$startArticleResult = $numPage * $articlesPerPage;
$articlesRepository = $this
->getDoctrine()
->getRepository( $repository );
$mappedBy = strtolower(explode( ':', $repository)[1][0]);
$allRecords = count($articlesRepository
->createQueryBuilder($mappedBy)
->orderBy( $mappedBy.'.'.$orderBy, $sortBy )
->getQuery()
->getResult()
);
$maxNumPage = floor( $allRecords / $articlesPerPage ) + 1;
$minNumPageDisplay = $numPage - 4;
$maxNumPageDisplay = $numPage + 5;
if( $minNumPageDisplay < 1){
$minNumPageDisplay = 1;
}
if( $maxNumPageDisplay > $maxNumPage){
$maxNumPageDisplay = $maxNumPage;
}
$articles = $articlesRepository
->createQueryBuilder($mappedBy)
->orderBy( $mappedBy.'.'.$orderBy, $sortBy )
->setFirstResult( $startArticleResult )
->setMaxResults( $articlesPerPage )
->getQuery()
->getResult();
$articlesResultRows = count($articles);
if( $articlesResultRows == 0 ){
return $this->render($twigTemplatePath,array(
'error'=> 'true',
'actualPage' => 'false',
'articles' => 'false',
'maxNumPageDisplay' => 'false',
'minNumPageDisplay' => 'false'
));
}
return $this->render($twigTemplatePath,array(
'error' => 'false',
'actualPage' => $numPage,
'articles' => $articles,
'maxNumPageDisplay' => $maxNumPageDisplay,
'minNumPageDisplay' => $minNumPageDisplay
));
}