3

I have customized a Layered navigation modules in Magento 2. However, I can't write a controller to get all content of category page and load into controller page(localhost/magento2/layerednavigation/index/index/id/17?cat=15&style_general=117).

The controller page will load but it don't filler product. I have checked and seen that controller page don't get param(cat, style_general....). Summary, I want write controller to load category page. However, I am facing the issue is the filler don't work into controller page.

Please refer code: 1. Code for layout: layerednavigation_index_index.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
    <referenceContainer name="columns.top">
        <container name="category.view.container" htmlTag="div" htmlClass="category-view" after="-">
            <block class="Magento\Catalog\Block\Category\View" name="category.image" template="Magento_Catalog::category/image.phtml"/>
            <block class="Magento\Catalog\Block\Category\View" name="category.description" template="Magento_Catalog::category/description.phtml"/>
            <block class="Magento\Catalog\Block\Category\View" name="category.cms" template="Magento_Catalog::category/cms.phtml"/>
        </container>
    </referenceContainer>
    <referenceContainer name="content">
        <block class="Magento\Catalog\Block\Category\View" name="category.products" template="Magento_Catalog::category/products.phtml">
            <block class="Magento\Catalog\Block\Product\ListProduct" name="category.products.list" as="product_list" template="Magento_Catalog::product/list.phtml">
                <container name="category.product.list.additional" as="additional" />
                <block class="Magento\Framework\View\Element\RendererList" name="category.product.type.details.renderers" as="details.renderers">
                    <block class="Magento\Framework\View\Element\Template" as="default"/>
                </block>
                <block class="Magento\Catalog\Block\Product\ProductList\Toolbar" name="product_list_toolbar" template="Magento_Catalog::product/list/toolbar.phtml">
                    <block class="Magento\Theme\Block\Html\Pager" name="product_list_toolbar_pager"/>
                    <!-- The following code shows how to set your own pager increments -->
                    <!--
                        <action method="setDefaultListPerPage">
                        <argument name="limit" xsi:type="string">4</argument>
                    </action>
                    <action method="setDefaultGridPerPage">
                        <argument name="limit" xsi:type="string">3</argument>
                    </action>
                    <action method="addPagerLimit">
                        <argument name="mode" xsi:type="string">list</argument>
                        <argument name="limit" xsi:type="string">2</argument>
                    </action>
                    <action method="addPagerLimit">
                        <argument name="mode" xsi:type="string">list</argument>
                        <argument name="limit" xsi:type="string">4</argument>
                    </action>
                    <action method="addPagerLimit">
                        <argument name="mode" xsi:type="string">list</argument>
                        <argument name="limit" xsi:type="string">6</argument>
                    </action>
                    <action method="addPagerLimit">
                        <argument name="mode" xsi:type="string">list</argument>
                        <argument name="limit" xsi:type="string">8</argument>
                    </action>
                    <action method="addPagerLimit" translate="label">
                        <argument name="mode" xsi:type="string">list</argument>
                        <argument name="limit" xsi:type="string">all</argument>
                        <argument name="label" xsi:type="string">All</argument>
                    </action>
                    <action method="addPagerLimit">
                        <argument name="mode" xsi:type="string">grid</argument>
                        <argument name="limit" xsi:type="string">3</argument>
                    </action>
                    <action method="addPagerLimit">
                        <argument name="mode" xsi:type="string">grid</argument>
                        <argument name="limit" xsi:type="string">6</argument>
                    </action>
                    <action method="addPagerLimit">
                        <argument name="mode" xsi:type="string">grid</argument>
                        <argument name="limit" xsi:type="string">9</argument>
                    </action>
                    <action method="addPagerLimit" translate="label">
                        <argument name="mode" xsi:type="string">grid</argument>
                        <argument name="limit" xsi:type="string">all</argument>
                        <argument name="label" xsi:type="string">All</argument>
                    </action>
                    -->
                </block>
                <action method="setToolbarBlockName">
                    <argument name="name" xsi:type="string">product_list_toolbar</argument>
                </action>
            </block>
        </block>
        <block class="Magento\Cookie\Block\RequireCookie" name="require-cookie" template="Magento_Cookie::require_cookie.phtml">
            <arguments>
                <argument name="triggers" xsi:type="array">
                    <item name="compareProductLink" xsi:type="string">.action.tocompare</item>
                </argument>
            </arguments>
        </block>
    </referenceContainer>
    <referenceBlock name="page.main.title">
        <arguments>
            <argument name="id" xsi:type="string">page-title-heading</argument>
            <argument name="add_base_attribute_aria" xsi:type="string">page-title-heading toolbar-amount</argument>
        </arguments>
        <block class="Magento\Catalog\Block\Category\Rss\Link" name="rss.link" template="Magento_Catalog::category/rss.phtml"/>
    </referenceBlock>
    </body>
</page>
  1. Controller code: index.php

    <?php
     namespace Emthemes\LayeredNavigationPro\Controller\Index;
     use Magento\Catalog\Api\CategoryRepositoryInterface;
     use Magento\Catalog\Model\Layer\Resolver;
     use Magento\Framework\Exception\NoSuchEntityException;
     use Magento\Framework\View\Result\PageFactory;
    
    class Index extends \Magento\Framework\App\Action\Action
    {
    protected $_coreRegistry = null;
    
    protected $_catalogSession;
    
    protected $_catalogDesign;
    
    protected $_storeManager;
    
    protected $categoryUrlPathGenerator;
    
    protected $resultPageFactory;
    
    protected $resultForwardFactory;
    
    private $layerResolver;
    
    protected $categoryRepository;
    
    /**
     * Constructor
     *
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Catalog\Model\Design $catalogDesign
     * @param \Magento\Catalog\Model\Session $catalogSession
     * @param \Magento\Framework\Registry $coreRegistry
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator $categoryUrlPathGenerator
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     * @param \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory
     * @param Resolver $layerResolver
     * @param CategoryRepositoryInterface $categoryRepository
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Catalog\Model\Design $catalogDesign,
    \Magento\Catalog\Model\Session $catalogSession,
    \Magento\Framework\Registry $coreRegistry,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator $categoryUrlPathGenerator,
    PageFactory $resultPageFactory,
    \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory,
    Resolver $layerResolver,
    CategoryRepositoryInterface $categoryRepository
    ) {
    parent::__construct($context);
    $this->_storeManager = $storeManager;
    $this->_catalogDesign = $catalogDesign;
    $this->_catalogSession = $catalogSession;
    $this->_coreRegistry = $coreRegistry;
    $this->categoryUrlPathGenerator = $categoryUrlPathGenerator;
    $this->resultPageFactory = $resultPageFactory;
    $this->resultForwardFactory = $resultForwardFactory;
    $this->layerResolver = $layerResolver;
    $this->categoryRepository = $categoryRepository;
    }
    
    /**
     * Initialize requested category object
     *
     * @return \Magento\Catalog\Model\Category
     */
    protected function _initCategory()
    {
    $categoryId = (int)$this->getRequest()->getParam('id', false);
    if (!$categoryId) {
        return false;
    }
    
    try {
        $category = $this->categoryRepository->get($categoryId, $this->_storeManager->getStore()->getId());
    } catch (NoSuchEntityException $e) {
        return false;
    }
    if (!$this->_objectManager->get('Magento\Catalog\Helper\Category')->canShow($category)) {
        return false;
    }
    $this->_catalogSession->setLastVisitedCategoryId($category->getId());
    $this->_coreRegistry->register('current_category', $category);
    try {
        $this->_eventManager->dispatch(
            'catalog_controller_category_init_after',
            ['category' => $category, 'controller_action' => $this]
        );
    } catch (\Magento\Framework\Exception\LocalizedException $e) {
        $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
        return false;
    }
    
    return $category;
    }
    
    /**
     * Category view action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
    if ($this->_request->getParam(\Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED)) {
        return $this->resultRedirectFactory->create()->setUrl($this->_redirect->getRedirectUrl());
    }
    $category = $this->_initCategory();
    if ($category) {
        $this->layerResolver->create(Resolver::CATALOG_LAYER_CATEGORY);
        $settings = $this->_catalogDesign->getDesignSettings($category);
    
        // apply custom design
        if ($settings->getCustomDesign()) {
            $this->_catalogDesign->applyCustomDesign($settings->getCustomDesign());
        }
    
        $this->_catalogSession->setLastViewedCategoryId($category->getId());
    
        $page = $this->resultPageFactory->create();
        // apply custom layout (page) template once the blocks are generated
        if ($settings->getPageLayout()) {
            $page->getConfig()->setPageLayout($settings->getPageLayout());
        }
    
        $hasChildren = $category->hasChildren();
        if ($category->getIsAnchor()) {
            $type = $hasChildren ? 'layered' : 'layered_without_children';
        } else {
            $type = $hasChildren ? 'default' : 'default_without_children';
        }
    
        if (!$hasChildren) {
            // Two levels removed from parent.  Need to add default page type.
            $parentType = strtok($type, '_');
            $page->addPageLayoutHandles(['type' => $parentType]);
        }
        $page->addPageLayoutHandles(['type' => $type, 'id' => $category->getId()]);
    
        // apply custom layout update once layout is loaded
        $layoutUpdates = $settings->getLayoutUpdates();
        if ($layoutUpdates && is_array($layoutUpdates)) {
            foreach ($layoutUpdates as $layoutUpdate) {
                $page->addUpdate($layoutUpdate);
                $page->addPageLayoutHandles(['layout_update' => md5($layoutUpdate)]);
            }
        }
    
        $page->getConfig()->addBodyClass('page-products')
            ->addBodyClass('categorypath-' . $this->categoryUrlPathGenerator->getUrlPath($category))
            ->addBodyClass('category-' . $category->getUrlKey());
    
        } 
        $block = $page->getLayout()->getBlock('category.products');
        $this->getResponse()->setBody($block->toHtml());
     }
    }
    

1 Answer 1

1

All you need to do is get category id from url and set in registery and use it in block,
This is what controller execute contains:

$catId = (int)$this->getRequest()->getParam('id', false);
$this->_coreRegistry->register('catid', $catId);

Here is the block function where you can access your registery category id and using it just fetch all categories :

Initialization:

       protected $_coreRegistry;
       private $_itemCollectionFactory;

Constructor :

public function __construct(
    ...
    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoriesCollection,
    \Magento\Framework\Registry $coreRegistry,
    ...
) {
    ...
    $this->_itemCollectionFactory = $categoriesCollection;
    $this->_coreRegistry = $coreRegistry;
    ...
}

And here is the function to get category list:

public function getCategoriesList()
{
    $cid = $this->_coreRegistry->registry('catid');

    $categoryFactory = $this->_itemCollectionFactory->create()
                            ->addAttributeToSelect('*');

    return $categoryFactory;
}
6
  • i have yet to filter into controller page. Could you show the instruction for me? Thanks for your help. I am a new Magento. Commented Nov 3, 2016 at 7:58
  • you can fetch category id from url in controller execute method, have you tried? Commented Nov 3, 2016 at 8:50
  • I have tried. However, it doesn't have respond. Could you help me, please? Commented Nov 3, 2016 at 9:00
  • sure, simply copy this line: $catId = (int)$this->getRequest()->getParam('cat', false); and print $catId and check what you are getting. you need to put this in controller execute method. Commented Nov 3, 2016 at 9:01
  • I have performed like you have guided. It don't effect to filter into controller page. Commented Nov 3, 2016 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.