Magento 2-계층 탐색 및 페이지 매김이있는 모든 제품 페이지


11

나는 모든 제품 페이지를 만들려면 filters, toolbar, pagination.

이름으로 새 카테고리를 작성하고 그 All Products안에 모든 제품을 지정 하여 수행 할 수 있습니다 . 그러나 새로운 제품이 웹 사이트에 추가 될 때마다 모든 제품 카테고리에도 추가되어야하는 것처럼 이것은 좋은 접근 방법이 아니라고 생각합니다. 인적 오류 가능성이 많습니다.

루트 레벨 카테고리로 카테고리 페이지를 호출하는 방법이 있습니까? ~에서처럼ID: 2

누군가가 나를 위해 코드를 작성하고 싶지 않다면 괜찮습니다. 그러나 누군가 내가 그것을 할 수있는 접근법을 찾도록 도울 수 있다면 좋을 것입니다.

답변:


12

나는 최근에 같은 종류의 일을했다. 먼저 모든 제품 페이지가 카테고리 페이지와 같기를 원하므로 카테고리 블록을 대체해야합니다. 더 이해하기 위해 현재 카테고리를 루트 카테고리로 설정하는 getCurrentCategory () 함수를 확인하십시오.

통로: app\code\Vendor\AllProducts\Block\Category\View.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Vendor\AllProducts\Block\Category;

/**
 * Class View
 * @api
 * @package Magento\Catalog\Block\Category
 * @since 100.0.2
 */
class View extends \Magento\Catalog\Block\Category\View
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * Catalog layer
     *
     * @var \Magento\Catalog\Model\Layer
     */
    protected $_catalogLayer;

    /**
     * @var \Magento\Catalog\Helper\Category
     */
    protected $_categoryHelper;

    protected $priceHelper;

    protected $_storeManager;

    protected $categoryRepository;

    protected $_request;

    protected $productFactory;

    protected $eavconfig;   
    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Catalog\Model\Layer\Resolver $layerResolver
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Catalog\Helper\Category $categoryHelper
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\Layer\Resolver $layerResolver,
        \Magento\Framework\Registry $registry,
        \Magento\Catalog\Helper\Category $categoryHelper,
        \Magento\Framework\Pricing\Helper\Data $priceHelper,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\CategoryRepository $categoryRepository,
        \Magento\Framework\App\Request\Http $request,
        \Magento\Catalog\Model\ResourceModel\ProductFactory $productFactory,
        \Magento\Eav\Model\Config $eavconfig,
        array $data = []
    ) {
        $this->_categoryHelper = $categoryHelper;
        $this->priceHelper = $priceHelper;
        $this->_catalogLayer = $layerResolver->get();
        $this->_coreRegistry = $registry;
        $this->_storeManager = $storeManager;
        $this->_request = $request;
        $this->categoryRepository = $categoryRepository;
        $this->productFactory = $productFactory;
        $this->eavconfig = $eavconfig;

        parent::__construct($context, $layerResolver, $registry, $categoryHelper, $data);
    }

    /**
     * @return $this
     */
    protected function _prepareLayout()
    {
        parent::_prepareLayout();


        $this->getLayout()->createBlock(\Magento\Catalog\Block\Breadcrumbs::class);

        $category = $this->getCurrentCategory();
        if ($category) {
            $title = $category->getMetaTitle();
            if ($title) {
                $this->pageConfig->getTitle()->set($title);
            }
            $description = $category->getMetaDescription();
            if ($description) {
                $this->pageConfig->setDescription($description);
            }
            $keywords = $category->getMetaKeywords();
            if ($keywords) {
                $this->pageConfig->setKeywords($keywords);
            }
            if ($this->_categoryHelper->canUseCanonicalTag()) {
                $this->pageConfig->addRemotePageAsset(
                    $category->getUrl(),
                    'canonical',
                    ['attributes' => ['rel' => 'canonical']]
                );
            }

            $pageMainTitle = $this->getLayout()->getBlock('page.main.title');
            if ($pageMainTitle) {
                $pageMainTitle->setPageTitle($this->getCurrentCategory()->getName());
            }
        }

        return $this;
    }

    /**
     * @return string
     */
    public function getProductListHtml()
    {
        return $this->getChildHtml('product_list');
    }

    /**
     * Retrieve current category model object
     *
     * @return \Magento\Catalog\Model\Category
     */

    //**** This function set the current category to root level category which is 2 in my case ****//
    public function getCurrentCategory()
    {
        if (!$this->hasData('current_category')) {

            if ($this->_request->getModuleName() == "allproducts"){
            $category = $this->categoryRepository->get(2, $this->_storeManager->getStore()->getId());
            }
            else {
            $category = $this->_coreRegistry->registry('current_category');
            }
            $this->setData('current_category', $category);
        }

        return $this->getData('current_category');
    }

    /**
     * @return mixed
     */
    public function getCmsBlockHtml()
    {
        if (!$this->getData('cms_block_html')) {
            $html = $this->getLayout()->createBlock(
                \Magento\Cms\Block\Block::class
            )->setBlockId(
                $this->getCurrentCategory()->getLandingPage()
            )->toHtml();
            $this->setData('cms_block_html', $html);
        }
        return $this->getData('cms_block_html');
    }

    /**
     * Check if category display mode is "Products Only"
     * @return bool
     */
    public function isProductMode()
    {
        return $this->getCurrentCategory()->getDisplayMode() == \Magento\Catalog\Model\Category::DM_PRODUCT;
    }

    /**
     * Check if category display mode is "Static Block and Products"
     * @return bool
     */
    public function isMixedMode()
    {
        return $this->getCurrentCategory()->getDisplayMode() == \Magento\Catalog\Model\Category::DM_MIXED;
    }

    /**
     * Check if category display mode is "Static Block Only"
     * For anchor category with applied filter Static Block Only mode not allowed
     *
     * @return bool
     */
    public function isContentMode()
    {
        $category = $this->getCurrentCategory();
        $res = false;
        if ($category->getDisplayMode() == \Magento\Catalog\Model\Category::DM_PAGE) {
            $res = true;
            if ($category->getIsAnchor()) {
                $state = $this->_catalogLayer->getState();
                if ($state && $state->getFilters()) {
                    $res = false;
                }
            }
        }
        return $res;
    }

    /**
     * Return identifiers for produced content
     *
     * @return array
     */
    public function getIdentities()
    {
        return $this->getCurrentCategory()->getIdentities();
    }
}

블록 경로 추가 : app\code\Vendor\AllProducts\Block\Index\Index.php

<?php

namespace Vendor\AllProducts\Block\Index;


class Index extends \Magento\Framework\View\Element\Template {

    public function __construct(\Magento\Catalog\Block\Product\Context $context, array $data = []) {

        parent::__construct($context, $data);

    }


    protected function _prepareLayout()
    {
        return parent::_prepareLayout();
    }

}

전면 컨트롤러를 추가하십시오. 경로는 다음과 같아야합니다. app\code\Vendor\AllProducts\Controller\Index\Index.php

<?php

namespace Vendor\AllProducts\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    private $context;
    private  $response;
    private  $redirect;
    /**
     * @var \Magento\Framework\UrlInterface
     */
    private $url;


    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\UrlInterface $url
    )
    {
        parent::__construct($context);
        $this->context = $context;
        $this->response = $context->getResponse();
        $this->redirect = $context->getRedirect();
        $this->url = $url;
        //return 
    }

    public function execute()
    {

        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
    }

    public function getResponse()
    {
        return $this->response;
    }
}

di.xml안내 경로를 재정의하기 위해 모듈에 추가하십시오 .app\code\Vendor\AllProducts\etc\di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Block\Category\View" type="Vendor\AllProducts\Block\Category\View" />
</config>

catalog_category_view.xml모듈을 재정의 하십시오. 경로는 다음과 같아야합니다.app\code\Vendor\AllProducts\view\frontend\layout\allproducts_index_index.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. 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="sidebar.main">
            <block class="Magento\LayeredNavigationStaging\Block\Navigation\Category" name="catalog.leftnav" before="-" template="Magento_LayeredNavigation::layer/view.phtml">
                <block class="Magento\LayeredNavigation\Block\Navigation\State" name="catalog.navigation.state" as="state" />
                <block class="Magento\LayeredNavigation\Block\Navigation\FilterRenderer" name="catalog.navigation.renderer" as="renderer" template="Magento_LayeredNavigation::layer/filter.phtml"/>
            </block>
        </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" name="category.product.type.details.renderers.default" as="default"/>
                    </block>
                    <block class="Magento\Catalog\Block\Product\ProductList\Item\Container" name="category.product.addto" as="addto">
                        <block class="Magento\Catalog\Block\Product\ProductList\Item\AddTo\Compare"
                               name="category.product.addto.compare" as="compare"
                               template="Magento_Catalog::product/list/addto/compare.phtml"/>
                    </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"/>
                    </block>
                    <action method="setToolbarBlockName">
                        <argument name="name" xsi:type="string">product_list_toolbar</argument>
                    </action>
                </block>
            </block>
        </referenceContainer>
    </body>
</page>

이것이 도움이되기를 바랍니다.


감사합니다. Muhammad,이 솔루션을 사용해 보겠습니다.
— 무하마드 파잠

감사합니다 :) 나를 위해 일한
— 무하마드 Farzam에게

@MuhammadHasham 레이아웃 표시가 잘못되어 견본 및 계층 탐색이 표시되지 않습니다. 그것을 해결하는 방법?
— Ankita Patel


@MuhammadHasham 카테고리 목록에도 하위 카테고리를 표시하고 싶습니다. 당신은 그것을 표시하는 방법을 알고 있습니까? 모든 제품 페이지에 "기본 카테고리"가 표시됩니다.
— Rohan Hapani
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.