Symfony Doctrine pagination script

Symfony paginator

Symfony paginator

We usually need database record pagination in symfony with filters. It is very simple and easy to implement in . The below code will be helpful for you to create pagination in Symfony.

Please add the following code in action.

$this->pager = new sfDoctrinePager('Myclass',10);
$this->pager->getQuery();
 
// If you have filers in the to apply in the db query add the following code 
$this->pager->getQuery()->from('Myclass a')->where('a.column_name LIKE ?' , '%'.$searchString.'%');
 
 $this->pager->setPage($this->getRequestParameter('page',1));
 $this->pager->init();
 
// Code to get the query string 
$this->queryString = $this->getContext()->getInstance()->getRouting()->getCurrentInternalUri();

It will be useful if you create a helper file to generate the navigation. Please add the following function to the helper file.

 
function pager_navigation($pager, $uri)
{
  $navigation = array();
 
  if ($pager->haveToPaginate())
  {
    $uri .= (preg_match('/\?/', $uri) ? '&' : '?').'page=';
 
    // First and previous page
    if ($pager->getPage() != 1)
    {
      $navigation[] = link_to('First', $uri.'1');
      $navigation[] = link_to('Previous', $uri.$pager->getPreviousPage());
    }
 
    // Pages one by one
    $links = array();
    foreach ($pager->getLinks() as $page)
    {
      $navigation[] = link_to_unless($page == $pager->getPage(), $page, $uri.$page);
    }
    // $navigation .= join('  ', $links);
 
    // Next and last page
    if ($pager->getPage() != $pager->getLastPage())
    {
      $navigation[] = link_to( 'Next', $uri.$pager->getNextPage());
      $navigation[] = link_to( 'Last', $uri.$pager->getLastPage());
    }
 
  }
 
  $returnHtml = "<ul id='pagination'>";
 
  foreach( $navigation  as $link )
  {
     $returnHtml .= "<li>".$link."</li>";
  }
 
  $returnHtml .= "</ul>";
  return $returnHtml;
 
}

You can call the above function from the template file. Also add the below code to display records.

    <?php foreach ($pager->getResults() as $record ): ?>
 
    <?php endforeach; ?>
 
// Show navigation 
<?php  echo pager_navigation( $pager, url_for( 'module/action?'.html_entity_decode($queryString) , true ) ); ?>

if you are looking for a quick styling the navigation you can use the following css styling for the pagination navigator links.

 
 
 
#pagination li{
	border:0;
	margin:0;
	padding: 0px; 
	font-size:12px;
	list-style:none;
	margin-right:5px;
	float: left;
	text-indent: 0px;
}
#pagination a{
	border:solid 1px #9aafe5;
	padding: 5px;
	display: block;
	text-decoration: none;
}
 
#pagination span {
	display: block;
	padding: 5px;
	color: #ffffff;
	font-weight:bold;
	background:#2e6ab1;
}
 
#pagination .active {
 
	background:#2e6ab1;
	color:#FFFFFF;
	font-weight:bold;
	display:block;
	float:left;
	padding:4px 6px;
}

Leave a Reply

Copyright © 2012 Mesmerizing Moments | sarathdr.com.