How To Get Items To Storefront In Magento 2

In the previous lesson, we learned together How To Use Model In Magento 2. Continuing that lesson, I will introduce How To Get Items To Storefront In Magento 2.

You should read the Magento 2 Extension Tutorial step by step to be able to understand this lesson.

Module File Structure

We updated our module file structure looks as follows:

How To Get Items To Storefront File Stucture

Create Controller

First, we create Lists.php with the following path: Magetop/Helloworld/Controller/Index/Lists.php

<?php
namespace Magetop\Helloworld\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Lists extends \Magento\Framework\App\Action\Action
{
    protected $_resultPageFactory;

    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    )
    {
        parent::__construct($context);
        $this->_resultPageFactory = $resultPageFactory;

    }

    public function execute()
    {
        $resultPageFactory = $this->_resultPageFactory->create();

        // Add page title
        $resultPageFactory->getConfig()->getTitle()->set(__('Posts List'));

        // Add breadcrumb
        /** @var \Magento\Theme\Block\Html\Breadcrumbs */
        if($resultPageFactory->getLayout()->getBlock('breadcrumbs'))
        {
            $breadcrumbs = $resultPageFactory->getLayout()->getBlock('breadcrumbs');
            $breadcrumbs->addCrumb('home',
                [
                    'label' => __('Home'),
                    'title' => __('Home'),
                    'link' => $this->_url->getUrl('')
                ]
            );
            $breadcrumbs->addCrumb('booking_search',
                [
                    'label' => __('Posts'),
                    'title' => __('Posts')
                ]
            );
        }
        return $resultPageFactory;
    }
}

Create layout

You create a layout file according to the path: Magetop/Helloworld/view/frontend/layout/helloworld_index_lists.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * helloworld_index_lists
 *
 * @copyright Copyright © 2020 Magetop. All rights reserved.
 * @author    [email protected]
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="Magetop_Helloworld::css/style.css" />
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Magetop\Helloworld\Block\Posts" name="magetop.helloworld.posts" template="Magetop_Helloworld::items.phtml" />
        </referenceContainer>
    </body>
</page>

As you can see, I have to define Block class (Magetop\Helloworld\Block\Posts) to get Data, phml file (items.phtml) to show data and (css/style.css) to style for page.

Get data with Block file

Next, we create Posts.php with the following path: Magetop/Helloworld/Block/Posts.php

<?php
namespace Magetop\Helloworld\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\Registry;

class Posts extends Template
{
    protected $_coreRegistry;

    protected $_postsFactory;

    public function __construct(
        Template\Context $context,
        Registry $coreRegistry,
        \Magetop\Helloworld\Model\ResourceModel\Posts\CollectionFactory $postsFactory,
        array $data = []
    )
    {

        parent::__construct($context, $data);
        $this->_coreRegistry = $coreRegistry;
        $this->_postsFactory = $postsFactory;
    }

    /**
     * @return $this|mixed
     */
    function getPostItems() {
        if($this->_coreRegistry->registry('post_items'))
        {
            $collection = $this->_coreRegistry->registry('post_items');
        }
        else {
            $collection = $this->_postsFactory->create()
                ->addFieldToSelect(array('title','description'))
                ->addFieldToFilter('status',1)
                ->setPageSize(10)
                ->setOrder('id','ASC');
            $this->_coreRegistry->register('post_items',$collection);
        }
        return $collection;

    }

}

Show data with phtml file

Create phtml file Magetop/Helloworld/view/frontend/templates/items.phtml.

<?php
/** @var \Magetop\Helloworld\Block\Posts $block*/
?>
<?php $posts = $block->getPostItems(); ?>
<div class="post-content">
    <table style="width:100%">
        <tr>
            <th><?php echo __('Title') ?></th>
            <th><?php echo __('Description') ?></th>
        </tr>
        <?php if(count($posts)) : ?>
            <?php foreach ($posts as $post) : ?>
                <tr>
                    <td><?php echo $post->getTitle() ?></td>
                    <td><?php echo $post->getDescription() ?></td>
                </tr>
            <?php endforeach; ?>
        <?php endif; ?>
    </table>
</div>

Create a CSS file

Create file according to the path: Magetop/Helloworld/view/frontend/web/css/style.css

table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}

You access the link created on the store page to check it out.

<yourdomain>/helloworld/index/lists
Show data to storefront

I hope through this series you can create your own complete module. Good luck!

In addition to How To Get Items To Storefront In Magento 2, you can read the articles How To Use Helper And Setting In Magento 2.

Follow us for the more helpful article!

We hope this is a useful series for you.

Thank you for reading!

5 3 votes
Article Rating

Aaron LX

Aaron is a passionate writer, crazy about shopping, eCommerce and trends. Besides his outstanding research skills and a positive mind, Aaron eagerly shares his experience with the readers.

Leave a Reply or put your Question here

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x