How to get Items to frontend in Magento 2 extension

I have done the most basic tasks in backend of extension in previous posts so you can manage,filter,add,update,delete items from Grid in backend. I will introduce How to get Items to frontend in Magento 2 extension. This is the tasks that we will show use for end user. It include 6 parts:

  • Create Controller
  • Create layout xml
  • Create Block
  • Show data in phtml file.
  • create file style

1. create Controller

In order to load items, you have to create a controller Lists in app/code/Magebay/Hello/Controller/Index

<?php
namespace Magebay\Hello\Controller\Index;
 
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

/**
 * Class Lists
 * @package Magebay\Hello\Controller\Index
 */
class Lists extends \Magento\Framework\App\Action\Action
{

    /**
     * Lists constructor.
     * @param Context $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    )
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
		
    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|\Magento\Framework\View\Result\Page
     */
    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;
    }
}
 

2. Create layout File

Next, We create layout file hello_index_lists.xml that define Block, phml file and you also can add css to page in the xml file

<?xml version="1.0" encoding="UTF-8"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="Magebay_Hello::css/style.css" />
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Magebay\Hello\Block\Posts" name="posts.search" template="Magebay_Hello::posts/items.phtml" />
        </referenceContainer>
    </body>
</page>

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

3. Create Block

  • Create file app/code/Magebay/Hello/Block/Posts.php to get data.
<?php

namespace Magebay\Hello\Block;

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

/**
 * Class Posts
 * @package Magebay\Hello\Block
 */
class Posts extends Template
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $coreRegistry;

    /**
     * @var \Magebay\Hello\Model\ResourceModel\Posts\CollectionFactory
     */
    protected $postsFactory;

    /**
     * Posts constructor.
     * @param Template\Context $context
     * @param Registry $coreRegistry
     * @param \Magebay\Hello\Model\ResourceModel\Posts\CollectionFactory $postsFactory
     * @param array $data
     */
    public function __construct(
        Template\Context $context,
        Registry $coreRegistry,
        \Magebay\Hello\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('position','ASC');
            $this->coreRegistry->register('post_items',$collection);
        }
        return $collection;

    }
    
}

4. Show data in phtml file.

  • Create file app/code/Magebay/Hello/view/frontend/templates/posts/items.phtml to show data
<?php
/** @var \Magebay\Hello\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>


5. Create File style

  • Create file app/code/Magebay/Hello/view/frontend/web/css/style.css to style for page
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}

Finally, You can see list when accessing to page yourdomain.com/hello/index/lists like screen image

How To use RequireJS and Ajax in Magento 2 Extension

Thank for reading the post How to get Items to frontend in Magento 2 extension. The task is very importance because this show data for end user so I hope you can ready more carefully and build a Magento 2 extension by your self. I will introduce how to user Require JS and Ajax in Magento 2 . This is necessary task when building Magento 2 extension.