0

I created a custom module to list all categories in a custom page. But the associated block is not getting called in the layout file. I can see the controller function is getting executed and page title is displayed properly.

<?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">
    <update handle="shop_shop" />
    <body>
        <referenceContainer name="content">
            <block class="Vendor\Shop\Block\CategoryList"
                name="vendor_shop_shop_list"
                template="vendor_Shop::list.phtml" />
        </referenceContainer>
    </body>
</page>

There is no error displayed.

Block code

<?php namespace Vendor\Shop\Block;

class CategoryList extends \Magento\Framework\View\Element\Template
{    
protected $_categoryCollectionFactory;
protected $_categoryHelper;

public function __construct(
    \Magento\Backend\Block\Template\Context $context,        
    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
    \Magento\Catalog\Helper\Category $categoryHelper,
    array $data = []
)
{
    $this->_categoryCollectionFactory = $categoryCollectionFactory;
    $this->_categoryHelper = $categoryHelper;
    parent::__construct($context, $data);
}

/**
 * Get category collection
 *
 * @param bool $isActive
 * @param bool|int $level
 * @param bool|string $sortBy
 * @param bool|int $pageSize
 * @return \Magento\Catalog\Model\ResourceModel\Category\Collection or array
 */
public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
{
    $collection = $this->_categoryCollectionFactory->create();
    $collection->addAttributeToSelect('*');        

    // select only active categories
    if ($isActive) {
        $collection->addIsActiveFilter();
    }

    // select categories of certain level
    if ($level) {
        $collection->addLevelFilter($level);
    }

    // sort categories by some value
    if ($sortBy) {
        $collection->addOrderField($sortBy);
    }

    // select certain number of categories
    if ($pageSize) {
        $collection->setPageSize($pageSize); 
    }    

    return $collection;
}

/**
 * Retrieve current store categories
 *
 * @param bool|string $sorted
 * @param bool $asCollection
 * @param bool $toLoad
 * @return \Magento\Framework\Data\Tree\Node\Collection or
 * \Magento\Catalog\Model\ResourceModel\Category\Collection or array
 */
public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
{
    return $this->_categoryHelper->getStoreCategories($sorted = false, $asCollection = false, $toLoad = true);
}
}

?>

Template path : Vendor/Shop/view/frontend/templates/list.phtml

<?php
    /**
     * @var \Vendor\Shop\Block\CategoryList $block
     */
    $categoryCollection = $block->getCategoryCollection();
?>
<ul>
    <?php foreach ($categoryCollection as $category) : ?>
        <li>
            <div class="category-list">
                <a class="news-title" href=""><?php echo $category->getTitle() ?></a>
           </div>
        </li>
     <?php endforeach; ?>
</ul>

Controller : Vendor/Shop/Controller/Index/index.php

<?php

namespace Vendor\Shop\Controller\Index;

use Vendor\Shop\Controller\Shop;

class Index extends Shop
{

}

Controller : Vendor/Shop/Controller/Shop.php

<?php

namespace Vendor\Shop\Controller;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Result\PageFactory;
use Vendor\Shop\Helper\Data;

class Shop extends Action
{
   /**
    * @var \Magento\Framework\View\Result\PageFactory
    */
   protected $_pageFactory;

   /**
    * @var \Tutorial\SimpleNews\Helper\Data
    */
   protected $_dataHelper;


   /**
    * @param Context $context
    * @param PageFactory $pageFactory
    * @param Data $dataHelper
    */
   public function __construct(
      Context $context,
      PageFactory $pageFactory,
      Data $dataHelper
   ) {
      parent::__construct($context);
      $this->_pageFactory = $pageFactory;
      $this->_dataHelper = $dataHelper;
   }

   /**
     * Dispatch request
     *
     * @param RequestInterface $request
     * @return \Magento\Framework\App\ResponseInterface
     */
    public function dispatch(RequestInterface $request)
    {
       // Check this module is enabled in frontend
      // if ($this->_dataHelper->isEnabledInFrontend()) {
          $result = parent::dispatch($request);
          return $result;
      // } else {
      //    $this->_forward('noroute');
      // }
    }

    public function execute()
    {
        $pageFactory = $this->_pageFactory->create();

        // Add title which is got by the configuration via backend
        $pageFactory->getConfig()->getTitle()->set(
            'This is the shop page'
        );

        // Add breadcrumb
        /** @var \Magento\Theme\Block\Html\Breadcrumbs */
        $breadcrumbs = $pageFactory->getLayout()->getBlock('breadcrumbs');
        $breadcrumbs->addCrumb('home',
            [
                'label' => __('Home'),
                'title' => __('Home'),
                'link' => $this->_url->getUrl('')
            ]
        );
        $breadcrumbs->addCrumb('simplenews',
            [
                'label' => __('Shop'),
                'title' => __('Shop')
            ]
        );

        return $pageFactory;
    }
}
2
  • share me block code as well templates paths. – sarvesh Dineshkumar Patel Jan 21 '20 at 7:20
  • @sarveshDineshkumarPatel Updated the question. – Sayanth Jan 21 '20 at 7:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.