Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use friendly URL with KnpPaginatorBundle

I installed KnpPaginatorBundle in my Symfony 2.1 project and also configure Paginator.

With pagination my URL looks like:

http://dev.localhost/app_dev.php/news/development?page=3

Is it possible to change URL to something like this (or similar - without ? and = character)?

http://dev.localhost/app_dev.php/news/development/page/3
like image 832
repincln Avatar asked Dec 26 '22 17:12

repincln


2 Answers

I found the solution, to solve your problem, follow these steps:

1) Create a new route or change the old one, so in the routing.yml add this:

news_development_route:
    pattern: /news/development/{page}
    defaults: {_controller: AcmeMainBundle:Article:list, page: 1 }

2) In your class controller, change your method like this:

// Acme\MainBundle\Controller\ArticleController.php

public function listAction($page)/*add the $page param*/
{
    $em    = $this->get('doctrine.orm.entity_manager');
    $dql   = "SELECT a FROM AcmeMainBundle:Article a";
    $query = $em->createQuery($dql);

    $paginator  = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $query,
        $this->get('request')->query->get('page', $page)/*change the number 1 by the $page parameter*/,
        10/*limit per page*/
    );
    $pagination->setUsedRoute('news_development_route'); /*define the pagination route*/

    // parameters to template
    return $this->render('AcmeMainBundle:Article:list.html.twig', array('pagination' => $pagination));
}

That's it

like image 190
Ali Aboussebaba Avatar answered Jan 05 '23 09:01

Ali Aboussebaba


In your controller, you need change this:

/**
 * @Route("/list/", name="_user_list")
 * @Template()
 */
public function listAction()
{
    $em = $this->get('doctrine.orm.entity_manager');
    $dql = "SELECT a FROM HPPTarjetaBundle:User a";
    $query = $em->createQuery($dql);

    $paginator = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $query,
        $this->get('request')->query->get('page', 1)/*page number*/,
        10/*limit per page*/
    );
    return compact('pagination');
}

... To this (see "page" parameter):

/**
 * @Route("/list/{page}", name="_user_list")
 * @Template()
 */
public function listAction($page)
{
    $em = $this->get('doctrine.orm.entity_manager');
    $dql = "SELECT a FROM HPPTarjetaBundle:User a";
    $query = $em->createQuery($dql);

    $paginator = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $query,
        $page/*page number*/,
        10/*limit per page*/
    );
    return compact('pagination');
}
like image 27
drmartin Avatar answered Jan 05 '23 11:01

drmartin