How to get the custom module collection?

How to display custom module collection data at frontend?

How to use Blocks to display custom module collection data at frontend?

How to display custom module collection data in list page and view page?

Magento, data interfaces, data models, and models.

This post will cover above all questions. I suppose you have inserted data into your custom table using Model, Resource Model. If you haven’t done it you may want to check my previous post click here.

Display custom module data list page Magento 2

Display custom module data list page Magento 2

Display custom module data view page Magento 2

Display custom module data view page Magento 2

In the previous post, we have inserted data into our custom module using a form at frontend. Now I am going to continue where we left in the previous post. So for me, I have a custom module Vky_Test so files will be for that module. Let’s get started.

Let’s say I want to display my custom module collection data in a list. Like if I run the URL – www.magento2.com/test/index/listdata the page should show the list. So we don’t have listdata action for our index controller in the custom module Vky_Test.

Display custom module collection data in the list page

Create Vky/Test/Controller/Index/ListData.php

<?php

namespace Vky\Test\Controller\Index;

class ListData extends \Magento\Framework\App\Action\Action
{
	public function execute()
    {
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
    }
}

We are using the layout in the action so we need to create a layout file for the list page.

Create Vky/Test/view/frontend/layout/test_index_listdata.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Vky\Test\Block\TestListData" name="test.listdata" template="Vky_Test::listdata.phtml">
            </block>
        </referenceContainer>
    </body>
</page>

In the layout file, we are using block – Vky\Test\Block\TestListData  and a phtml file – Vky_Test::listdata.phtml . So we need to create both.

Create Vky/Test/Block/TestListData.php

<?php

namespace Vky\Test\Block;

use Magento\Framework\View\Element\Template\Context;
use Vky\Test\Model\TestFactory;
/**
 * Test List block
 */
class TestListData extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        Context $context,
        TestFactory $test
    ) {
        $this->_test = $test;
        parent::__construct($context);
    }

    public function _prepareLayout()
    {
        $this->pageConfig->getTitle()->set(__('Simple Custom Module List Page'));
        
        return parent::_prepareLayout();
    }

    public function getTestCollection()
    {
        $test = $this->_test->create();
        $collection = $test->getCollection();
        return $collection;
    }
}

In the block file, we are setting a page title and getting the collection of our custom module in getTestCollection() function. We will return this collection from here so we can use it in our listdata.phtml file for the list page.

Create Vky/Test/view/frontend/templates/listdata.phtml

<?php
    $collection = $this->getTestCollection();
?>
<table class="data table" id="test-data-table">
    <caption class="table-caption">Vky Test Data</caption>
    <thead>
        <tr>
            <th scope="col" class="col title">Title</th>
            <th scope="col" class="col author">Author</th>
            <th scope="col" class="col content">Content</th>
            <th scope="col" class="col created_at">Created At</th>
            <th scope="col" class="col actions">Action</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($collection as $key => $data): ?>
            <tr>
                <td data-th="Title" class="col title"><?php echo $data->getTitle(); ?></td>
                <td data-th="Author" class="col author"><?php echo $data->getAuthor(); ?></td>
                <td data-th="Content" class="col content"><?php echo $data->getContent(); ?></td>
                <td data-th="Date" class="col created_at"><?php echo $data->getCreatedAt(); ?></td>
                <td data-th="Actions" class="col actions">
                    <a href="<?php echo $block->getBaseUrl().'test/index/view/id/'.$data->getTestId(); ?>" class="action view">
                        <span>View</span>
                    </a>
                </td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

In this file, we are getting the collection using our TestListData block and displayed in the data table. This is it for the list page. Run below commands from your root directory.

php bin/magento setup:upgrade
php bin/magento cache:flush

Check the URL – www.magento2.com/test/index/listdata. You should have the list of your data in the data table. There is an action column in the data table which is for the view of a single data. So we need to work on that.

Display custom module collection data in the view page

To display a single record we want our URL to be this – www.magento2.com/test/index/view/id/1 where we are passing the id of the record in the URL. So we will need a View action, the layout file, a block, a phtml file.

Create Vky/Test/Controller/Index/View.php

<?php

namespace Vky\Test\Controller\Index;

class View extends \Magento\Framework\App\Action\Action
{
	public function execute()
    {
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
    }
}

Create Vky/Test/view/frontend/layout/test_index_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Vky\Test\Block\TestView" name="test.view" template="Vky_Test::view.phtml">
            </block>
        </referenceContainer>
    </body>
</page>

Create Vky/Test/Block/TestView.php

<?php

namespace Vky\Test\Block;

use Magento\Framework\View\Element\Template\Context;
use Vky\Test\Model\TestFactory;
/**
 * Test View block
 */
class TestView extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        Context $context,
        TestFactory $test
    ) {
        $this->_test = $test;
        parent::__construct($context);
    }

    public function _prepareLayout()
    {
        $this->pageConfig->getTitle()->set(__('Simple Custom Module View Page'));
        
        return parent::_prepareLayout();
    }

    public function getSingleData()
    {
        $id = $this->getRequest()->getParam('id');
        $test = $this->_test->create();
        $singleData = $test->load($id);
        return $singleData;
    }
}

Here we are getting the id from the URL then load the single record and returning it to the view.phtml file using getSingleData() function.

Create Vky/Test/view/frontend/templates/view.phtml

<?php
	$singleData = $this->getSingleData();
?>
<div>
	<h3>Title</h3>
	<p><?php echo $singleData->getTitle(); ?></p>	
</div>
<div>
	<h3>Author</h3>
	<p><?php echo $singleData->getAuthor(); ?></p>
</div>
<div>
	<h3>Content</h3>
	<p><?php echo $singleData->getContent(); ?></p>
</div>
<div>
	<h3>Date</h3>
	<p><?php echo $singleData->getCreatedAt(); ?></p>
</div>

It’s Done. Run below commands from your root directory.

php bin/magento setup:upgrade
php bin/magento cache:flush

Now you can click on the View from the action column in the data table. A single record should display on your view page.

That’s how you display data in Magento 2. I hope it helps. See you later.

Next: How to add pagination for custom collection in Magento 2
(Check the post)

 

2 Comments
  • Nagaratna Hegde
    Posted at 09:55h, 26 April Reply

    Can i know how to display the data entered in the from in the next page with the message “You have saved the data” in the frontend ?

  • tejal pandit
    Posted at 09:53h, 30 April Reply

    while displaying the data at frontend of specific id, it shows fatal error.
    I want to show the data into CMS custome page at frotend. Here it is taking value of id from url, but i want to pass id as parameter in view.phtml file. How do i do this?

Post A Comment