Create latest news block via frontend in Magento 2

13 Oct 2015
Today, I will continue introducing you how to create latest news block and use the configuration via backend to display it (Left, Right, Disable) with Magento 2 Frontend. We will use the Tutorial_SimpleNews module in the last post.

Hi guys,

Today, I will continue introducing you about working with Magento 2 Frontend. We will use the Tutorial_SimpleNews module in the last post.

This is the summary after we finish this part:

- Create latest news block and use the configuration via backend to display it (Left, Right, Disable).

In order to understand this tutorial thoroughly, please review our last tutorials:

  1. How to create a simple module in Magento 2
  2. Create a module with custom database table in Magento 2
  3. How to use Model and Collection in Magento 2
  4. How to create the configuration via backend for a custom module
  5. Adding new menu item via backend in custom module
  6. Grid and Form in Magento 2 Admin Panel (Part 1)
  7. Grid and Form in Magento 2 Admin Panel (Part 2)
  8. Create the news list page via Frontend in Magento 2
  9. Create the news detail page via Frontend in Magento 2

 

Ok, now let’s get started!

 

We will create a block to display 5 latest posts via frontend:

Step 1: Create layout file

- Open file: app/code/Tutorial/SimpleNews/view/frontend/layout/news_news.xml (we will add 2 blocks to the page body) and insert this following code into it:

<?xml version="1.0" encoding="UTF-8"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="3columns"
xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/
Framework/View/Layout/etc/page_configuration.xsd">
   <head>
      <css src="Tutorial_SimpleNews::css/style.css" />
   </head>

    <body>
       <referenceContainer name="sidebar.main">
         <block class="Tutorial\SimpleNews\Block\Lastest\Left" name="lestest.news.left"
             before="-" />
       </referenceContainer>

       <referenceContainer name="sidebar.additional">
         <block class="Tutorial\SimpleNews\Block\Lastest\Right" name="lestest.news.right"
             before="-" />
       </referenceContainer>
    </body>
</page>

 

Step 2: Create block files

- Create file: app/code/Tutorial/SimpleNews/Block/Lastest.php (this file will get the news data) and insert this following code into it:

<?php

namespace Tutorial\SimpleNews\Block;

use Magento\Framework\View\Element\Template;
use Tutorial\SimpleNews\Helper\Data;
use Tutorial\SimpleNews\Model\NewsFactory;
use Tutorial\SimpleNews\Model\System\Config\Status;

class Lastest extends Template
{
   /**
    * @var \Tutorial\SimpleNews\Helper\Data
    */
   protected $_dataHelper;

   /**
    * @var \Tutorial\SimpleNews\Model\NewsFactory
    */
   protected $_newsFactory;

   /**
    * @param Template\Context $context
    * @param Data $dataHelper
    * @param NewsFactory $newsFactory
    */
   public function __construct(
      Template\Context $context,
      Data $dataHelper,
      NewsFactory $newsFactory
   ) {
      $this->_dataHelper = $dataHelper;
      $this->_newsFactory = $newsFactory;
      parent::__construct($context);
   }

   /**
    * Get five latest news
    *
    * @return \Tutorial\SimpleNews\Model\Resource\News\Collection
    */
   public function getLatestNews()
   {
      // Get news collection
      $collection = $this->_newsFactory->create()->getCollection();
      $collection->addFieldToFilter(
         'status',
         ['eq' => Status::ENABLED]
      );
      $collection->getSelect()
         ->order('id DESC')
         ->limit(5);

      return $collection;
   }
}

 

- Create file: app/code/Tutorial/SimpleNews/Block/Lastest/Left.php (This file will check the left position and set template file) and insert this following code into it:

<?php

namespace Tutorial\SimpleNews\Block\Lastest;

use Tutorial\SimpleNews\Block\Lastest;
use Tutorial\SimpleNews\Model\System\Config\LastestNews\Position;

class Left extends Lastest
{
   public function _construct()
   {
      $position = $this->_dataHelper->getLastestNewsBlockPosition();
      // Check this position is applied or not
      if ($position == Position::LEFT) {
         $this->setTemplate('Tutorial_SimpleNews::lastest.phtml');
      }
   }
}

 

- Create file: app/code/Tutorial/SimpleNews/Block/Lastest/Right.php (This file will check the right position and set template file) and insert this following code into it:

<?php

namespace Tutorial\SimpleNews\Block\Lastest;

use Tutorial\SimpleNews\Block\Lastest;
use Tutorial\SimpleNews\Model\System\Config\LastestNews\Position;

class Right extends Lastest
{
   public function _construct()
   {
      $position = $this->_dataHelper->getLastestNewsBlockPosition();
      // Check this position is applied or not
      if ($position == Position::RIGHT) {
         $this->setTemplate('Tutorial_SimpleNews::lastest.phtml');
      }
   }
}

 

Step 3: Create template file.

- Create file: app/code/Tutorial/SimpleNews/view/frontend/templates/lastest.phtml (This file will display 5 lastest news on the page) and insert this following code into it:

<?php
   $latestNews = $block->getLatestNews();
   if ($latestNews->getSize() > 0) :
?>
   <div class="block block-simplenews">
      <div class="block-title">
         <strong class="block-simplenews-heading"><?php echo __('Latest News') ?></strong>
      </div>

      <div class="block-content">
         <?php foreach ($latestNews as $news) : ?>
            <div>
               <span>+ </span>
               <a href="<?php echo $this->getUrl('news/index/view', ['id' => $news->getId()])
?>">
                  <span><?php echo $news->getTitle() ?></span>
               </a>
            </div>
         <?php endforeach; ?>
      </div>
   </div>
<?php endif; ?>

 

Ok, it’s done. You can see your result by accessing this url: http://yourdomain.com/news

 

Finally, we have finished this tutorial, and I hope it’s useful for you. See you again in our next Magento 2 tutorials.

Enjoy Magento 2 challenge with MageWorld’s tutorials! Follow our facebook fanpage for further discussion. 

Related Posts

Create the news detail page via frontend in Magento 2

Create the news detail page via frontend in Magento 2

07 Oct 2015
Today, I will continue introducing you about working with Magento 2 Frontend. We will continue using the Tutorial_SimpleNews module in the last post.
Create the news list page via frontend in Magento 2

Create the news list page via frontend in Magento 2

05 Oct 2015
We are happy to introduce you a series of tutorial on how to display data via frontend in Magento 2.This series is quite long then we will divide it into several parts.
Grid and Form in Magento 2 Admin Panel (Part 2)

Grid and Form in Magento 2 Admin Panel (Part 2)

25 Sep 2015
Today, I will continue introducing you how to create a Form via Magento 2 backend in custom module.
Grid and Form in Magento 2 Admin Panel (Part 1)

Grid and Form in Magento 2 Admin Panel (Part 1)

17 Sep 2015
In this 6th tutorial, I will introduce you how to create data grid and form via Magento 2 backend in custom module. This tutorial is quite long then we will divide it into several parts.