Back to Top

Magento2: Create list with pager in frontend

Updated 22 February 2024

Here we create list of record with pager in frontend for  magento2.

Before starting the code section, let us create the directory structure that we will need for list of record with pager in frontend.

*Note:- for complete module also include directory structure of blog Create Grid , edit/add grid row and installer in Magento2 .

app/code/Webkul/Grid/Block
app/code/Webkul/Grid/Controllers/Index
app/code/Webkul/Grid/etc/frontend
app/code/Webkul/Grid/view/frontend
app/code/Webkul/Grid/view/frontend/layout
app/code/Webkul/Grid/view/frontend/templates

as our previous blog Create Grid , edit/add grid row and installer in Magento2 we have already a working Model of table from where we save and retrieve data as record. now here we learn how to display these data in list with pager in frontend .

Searching for an experienced
Magento Company ?
Find out More

Now, as we have the directory structure ready, we will now create file as per module requirement in given sequence:

1.First, we have to create the block file named Index.php in app/code/Webkul/Grid/Block

<?php
namespace Webkul\Grid\Block;
class Index extends \Magento\Framework\View\Element\Template
{
     protected $_gridFactory; 
     public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Webkul\Grid\Model\GridFactory $gridFactory,
        array $data = []
     ) {
        $this->_gridFactory = $gridFactory;
        parent::__construct($context, $data);
        //get collection of data 
        $collection = $this->_gridFactory->create()->getCollection();
        $this->setCollection($collection);
        $this->pageConfig->getTitle()->set(__('My Grid List'));
    }
 
    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        if ($this->getCollection()) {
            // create pager block for collection 
            $pager = $this->getLayout()->createBlock(
                'Magento\Theme\Block\Html\Pager',
                'webkul.grid.record.pager'
            )->setCollection(
                $this->getCollection() // assign collection to pager
            );
            $this->setChild('pager', $pager);// set pager block in layout
        }
        return $this;
    }
 
    /**
     * @return string
     */
    // method for get pager html
    public function getPagerHtml()
    {
        return $this->getChildHtml('pager');
    }   
}
?>

2. Now, we will create a layout  file for list display  named grid_index_index.xml in app/code/Webkul/Grid/view/frontend/layout

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="3columns" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<body>
    <referenceContainer name="content">
         <!-- "Webkul\Grid\Block\Index" is block class which one we created in step 1 for retrieve data  -->              
        <block class="Webkul\Grid\Block\Index" name="Grid" template="Webkul_Grid::grid/success.phtml">
        </block>
    </referenceContainer>
</body>
</page>

In above layout xml file we mention that ‘template=”Webkul_Grid::grid/success.phtml” ‘ that mean Webkul_Grid is module name and grid/success.phtml is path of template file which is in template folder of this module.

3. Now, we will create a template  file for display list and pager named success.phtml in app/code/Webkul/Grid/view/frontend/template/grid

<?php
/** here you can get block class object by "$this" or "$block"  **/
/** here i'll use "$block" for get block object **/

$_gridrecords = $block->getCollection(); // get collection which we set in block class ?>
<?php if ($_gridrecords && count($_gridrecords)): ?>
    <div class="table-wrapper orders-history">
        <table class="data table table-order-items history" id="my-orders-table">
            <caption class="table-caption"><?php echo __('Grid Record') ?></caption>
            <thead>
                <tr>
                    <th scope="col" class="col id"><?php echo __('ID #') ?></th>
                    <th scope="col" class="col title"><?php echo __('Title') ?></th>
                    <th scope="col" class="col date"><?php echo __('Publish Date') ?></th>
                    <th scope="col" class="col status"><?php echo __('Status') ?></th>
                    <th scope="col" class="col ">&nbsp;</th>
                </tr>
            </thead>
            <tbody>
                <?php  // read collection as magento1.x and display in list 
                       foreach ($_gridrecords as $_gridrecord): ?>
                    <tr>
                        <td class="col id"><?php echo $_gridrecord->getId() ?></td>
                        <td class="col shipping"><?php echo $_gridrecord->getTitle() ?></td>
                        <td class="col date"><?php echo $block->formatDate($_gridrecord->getPublishDate()) ?></td>
                        <td class="col status"><?php echo $_gridrecord->getIsActive() ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if ($block->getPagerHtml()): ?>
        <div class="order-products-toolbar toolbar bottom"><?php echo $block->getPagerHtml(); // for display pager block which we create in block file.   ?></div>
    <?php endif ?>
<?php else: ?>
    <div class="message info empty"><span><?php echo __('grid records not available.'); ?></span></div>
<?php endif ?>

4.Now, we have to create the frontend controller  file.In Magento2, we need to create separate file for each action of frontend under the Controller folder. file named Index.php in app/code/Webkul/Grid/Controller/Index

<?php
namespace Webkul\Grid\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
  public function execute()
  {
	 $this->_view->loadLayout();
	 $this->_view->renderLayout();
  }
}
?>

5. Now, we will create a route configuration file for frontend  named routes.xml in app/code/Webkul/Grid/etc/frontend

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
    <route id="grid" frontName="grid">
        <module name="Webkul_Grid" />
    </route>
</router>
</config>

6. Now our frontend controller is ready when you open “localhost/magento2/grid” then your controller run and output display as following with list of record and pager.

Selection_020

here ‘locahost/magento2’ is magento2 base url and grid is controller on which record list display with pager.

and now we learned Magento2: Create list with pager in frontend 🙂

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


4 comments

  • Sarvesh Tiwari
    • shivam.rajpoot200 (Moderator)
  • Priya Ponnusamy
    • HimansuPatel
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home