Building a Paginated Data Table on the Magento Storefront
Customer portals often need a table of records, such as orders, registrations or documents, with paging. Magento 1 does not ship a frontend grid, but you can build one from a layout handle, a controller, a block and the standard pager.
1. Layout
Create app/design/frontend/base/default/layout/modulename.xml:
<layout version="0.1.0"> <modulename_index_index> <reference name="content"> <block type="modulename/blockname" name="modulename" template="modulename/modulename.phtml" /> </reference> </modulename_index_index> </layout>
2. Controller
app/code/local/Packagename/Modulename/controllers/IndexController.php:
class Packagename_Modulename_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->loadLayout();
$this->renderLayout();
}
}
3. Block
app/code/local/Packagename/Modulename/Block/Blockname.php loads the collection:
class Packagename_Modulename_Block_Blockname extends Mage_Core_Block_Template
{
public function __construct()
{
parent::__construct();
$collection = Mage::getModel('modelname/modelname')->getCollection();
$this->setCollection($collection);
}
}
4. Template
<?php echo $this->getPagerHtml() ?>
<table id="my-data-table" class="data-table">
<colgroup>
<col width="1">
<col width="1">
<col>
</colgroup>
<thead>
<tr class="first last">
<th><?php echo $this->__('No.')?></th>
<th><?php echo $this->__('Name')?></th>
<th><?php echo $this->__('Time')?></th>
</tr>
</thead>
<tbody>
<?php foreach($this->getCollection() as $data): ?>
<tr>
<td><?php echo $person->getData('id')?></td>
<td><?php echo $person->getData('name')?></td>
<td><?php echo Mage::helper('core')->formatDate($data->getData('time'))?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php echo $this->getPagerHtml() ?>
<script type="text/javascript">decorateTable('my-data-table')</script>
5. Add the pager
Back in the block, attach Magento’s pager to the collection:
public function _prepareLayout()
{
parent::_prepareLayout();
$pager = $this->getLayout()->createBlock('page/html_pager', 'block.pager')->setCollection($this->getCollection());
$this->setChild('pager', $pager);
return $this;
}
public function getPagerHtml()
{
return $this->getChildHtml('pager');
}
Heads up: this guide applies to Magento 1, which stopped receiving official security updates in June 2020. If your store still runs it, plan a move to Magento 2 or Adobe Commerce soon. We can help with the migration.
Want this done for you? Find out more about our Magento development service.