Friday, November 23, 2012
Create custom pagination in magento
Hope you known about block, xml in Magento.
Here is an extracted code that would help you to create pagination with custom collection in magento.
>> First paste the following code in your block class (e.g. product.php)
<?php
class example extends parentclass
{
private $_itemPerPage = 2;
private $_pageFrame = 8;
private $_curPage = 1;
public function getCollection($collection = 'null')
{
if($collection != 'null'){
$page = $this->getRequest()->getParam('p');
if($page) $this->_curPage = $page;
$collection->setCurPage($this->_curPage);
$collection->setPageSize($this->_itemPerPage);
return $collection;
}
}
public function getPagerHtml($collection = 'null')
{
$html = false;
if($collection == 'null') return;
if($collection->count() > $this->_itemPerPage)
{
$curPage = $this->getRequest()->getParam('p');
$pager = (int)($collection->count() / $this->_itemPerPage);
$count = ($collection->count() % $this->_itemPerPage == 0) ? $pager : $pager + 1 ;
$url = $this->getPagerUrl();
$start = 1;
$end = $this->_pageFrame;
$html .= '<ol>';
if(isset($curPage) && $curPage != 1){
$start = $curPage - 1;
$end = $start + $this->_pageFrame;
}else{
$end = $start + $this->_pageFrame;
}
if($end > $count){
$start = $count - ($this->_pageFrame-1);
}else{
$count = $end-1;
}
for($i = $start; $i<=$count; $i++)
{
if($i >= 1){
if($curPage){
$html .= ($curPage == $i) ? '<li class="current">'. $i .'</li>' : '<li><a href="'.$url.'&p='.$i.'">'. $i .'</a></li>';
}else{
$html .= ($i == 1) ? '<li class="current">'. $i .'</li>' : '<li><a href="'.$url.'&p='.$i.'">'. $i .'</a></li>';
}
}
}
$html .= '</ol>';
}
return $html;
}
public function getPagerUrl() // You need to change this function as per your url.
{
$cur_url = mage::helper('core/url')->getCurrentUrl();
$new_url = preg_replace('/\&p=.*/', '', $cur_url);
return $new_url;
}
}
?>
>> Now you have to modify your frontend phtml page. (e.g. custom.phtml)
<?php
$_collections = $this->getProductCollection(); // Default Collection on which you'll implement pagination.
$_productCollection = $this->getCollection($_collections); // calling the function that have been created in block page.
foreach ($_productCollection as $_product):
------------------ Your code here ------------
endforeach;
?>
<?php if($this->getPagerHtml($this->getProductCollection())):?> // pass the default collection as parameter
<div class="pages">
<span><?php echo $this->__('Page : ');?></span>
<?php echo $this->getPagerHtml($this->getProductCollection());?>
</div>
<?php endif;?>
Subscribe to:
Post Comments (Atom)
awesome saved tons of time thanks
ReplyDelete