2

I want override a block class, for this I have made entry in di.xml using preference and created a respective file on my custom module block/Rewrite/Product/ListProduct. My file is calling but now here apart from modify other functions I also need to modify __construct() function of base class. But I don't know how to do it


namespace Mageplaza\HelloWorld\Block\Rewrite\Product;
//use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Block\Product\ProductList\Toolbar;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Config;
use Magento\Catalog\Model\Layer;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Catalog\Pricing\Price\FinalPrice;
use Magento\Eav\Model\Entity\Collection\AbstractCollection;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\Config\Element;
use Magento\Framework\Data\Helper\PostHelper;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Pricing\Render;
use Magento\Framework\Url\Helper\Data;
use Magento\Framework\App\Request\Http;

 class ListProduct extends \Magento\Catalog\Block\Product\ListProduct
    {

      protected $_defaultToolbarBlock = Toolbar::class;

    /**
     * Product Collection
     *
     * @var AbstractCollection
     */
    protected $_productCollection;

    /**
     * Catalog layer
     *
     * @var Layer
     */
    protected $_catalogLayer;

    /**
     * @var PostHelper
     */
    protected $_postDataHelper;

    /**
     * @var Data
     */
    protected $urlHelper;
    protected $request;
    /**
     * @var CategoryRepositoryInterface
     */
    protected $categoryRepository;
    //        public function __construct(
    //     \Magento\Catalog\Block\Product\Context $context,
    //     PostHelper $postDataHelper,
    //     Resolver $layerResolver,
    //     CategoryRepositoryInterface $categoryRepository,
    //     Data $urlHelper,
    //     Http $request,
    //     array $data = []
    // ) {
    //     $this->_catalogLayer = $layerResolver->get();
    //     $this->_postDataHelper = $postDataHelper;
    //     $this->categoryRepository = $categoryRepository;
    //     $this->urlHelper = $urlHelper;
    //     parent::__construct(
    //         $context,$postDataHelper,$layerResolver,$categoryRepository,$urlHelper,$request,$data);
    // }

    public function initializeProductCollection(){
        echo "stringjhhj";
        echo $categoryId = $this->request->getParam('myselection'); // all params

            $layer = $this->getLayer();
        /* @var $layer Layer */
        if ($this->getShowRootCategory()) {
            $this->setCategoryId($this->_storeManager->getStore()->getRootCategoryId());
        }

        // if this is a product view page
        if ($this->_coreRegistry->registry('product')) {
            // get collection of categories this product is associated with
            $categories = $this->_coreRegistry->registry('product')
                ->getCategoryCollection()->setPage(1, 1)
                ->load();
            // if the product is associated with any category
            if ($categories->count()) {
                // show products from this category
                $this->setCategoryId(current($categories->getIterator())->getId());
            }
        }

        $origCategory = null;
        if ($this->getCategoryId()) {
            try {
             $category = $this->categoryRepository->get($this->getCategoryId());
             var_dump( $category);die;
            } catch (NoSuchEntityException $e) {
               echo $category = null;
            }

            if ($category) {
                $origCategory = $layer->getCurrentCategory();
                $layer->setCurrentCategory($category);
            }
        }
        $collection = $layer->getProductCollection();
        var_dump($collection->getData());

        $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());

        if ($origCategory) {
            $layer->setCurrentCategory($origCategory);
        }

        //$this->addToolbarBlock($collection);

        $this->_eventManager->dispatch(
            'catalog_block_product_list_collection',
            ['collection' => $collection]
        );

        return $collection;
        }

        public function  _getProductCollection(){
    // make changes here means call MyinitializeProductCollection in place of initializeProductCollection
            if ($this->_productCollection === null) {
            $this->_productCollection = $this->initializeProductCollection();
        }

        return $this->_productCollection;
        }

        public function getLoadedProductCollection(){
            // make changes here means call _MygetProductCollection in place of _getProductCollection
           // die("jhsjf");
        return $this->_getProductCollection();

        }
}

di.xml


Update :

Error :

Fatal error: Uncaught TypeError: Argument 1 passed to Mageplaza\HelloWorld\Block\Rewrite\Product\ListProduct::__construct() must be an instance of Mageplaza\HelloWorld\Block\Rewrite\Product\Context, instance of Magento\Catalog\Block\Product\Context given, called in /var/www/html/trainees/pooja_new/Magento22/generated/code/Mageplaza/HelloWorld/Block/Rewrite/Product/ListProduct/Interceptor.php on line 14 and defined in /var/www/html/trainees/pooja_new/Magento22/app/code/Mageplaza/HelloWorld/Block/Rewrite/Product/ListProduct.php:55 Stack trace: #0 /var/www/html/trainees/pooja_new/Magento22/generated/code/Mageplaza/HelloWorld/Block/Rewrite/Product/ListProduct/Interceptor.php(14): Mageplaza\HelloWorld\Block\Rewrite\Product\ListProduct->__construct(Object(Magento\Catalog\Block\Product\Context), Object(Magento\Framework\Data\Helper\PostHelper), Object(Magento\Catalog\Model\Layer\Resolver), Object(Magento\Catalog\Model\CategoryRepository), Object(Magento\Framework\Url\Helper\Data), Array) #1 /var/www/html/trainees/pooja_new/Magen in /var/www/html/trainees/pooja_new/Magento22/app/code/Mageplaza/HelloWorld/Block/Rewrite/Product/ListProduct.php on line 55

5
  • Can you update the error to your question? Also post the di.xml as well. Dec 27, 2018 at 11:34
  • Fatal error: Uncaught TypeError: Argument 1 passed to Mageplaza\HelloWorld\Block\Rewrite\Product\ListProduct::__construct() must be an instance of Mageplaza\HelloWorld\Block\Rewrite\Product\Context, instance of Magento\Catalog\Block\Product\Context given, called in /var/www/html/trainees/pooja_new/Magento22/generated/code/Mageplaza/HelloWorld/Block/Rewrite/Product/ListProduct/Interceptor.php on line 14 and defined in /var/www/html/trainees/pooja_new/Magento22/app/code/Mageplaza/HelloWorld/Block/Rewrite/Product/ListProduct.php:55 Stack trace:
    – ragini
    Dec 27, 2018 at 12:56
  • di.xml <preference for="Magento\Catalog\Block\Product\ListProduct" type="Mageplaza\HelloWorld\Block\Rewrite\Product\ListProduct"/>
    – ragini
    Dec 27, 2018 at 12:57
  • Try to compile : php bin/magento setup:di:compile
    – PЯINCƎ
    Dec 27, 2018 at 13:03
  • i did but nothing happend
    – ragini
    Dec 28, 2018 at 7:53

1 Answer 1

1

You can try the following code:

namespace Mageplaza\HelloWorld\Block\Rewrite\Product;

use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Block\Product\ProductList\Toolbar;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Config;
use Magento\Catalog\Model\Layer;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Catalog\Pricing\Price\FinalPrice;
use Magento\Eav\Model\Entity\Collection\AbstractCollection;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\Config\Element;
use Magento\Framework\Data\Helper\PostHelper;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Pricing\Render;
use Magento\Framework\Url\Helper\Data;
use Magento\Framework\App\Request\Http;

class ListProduct extends \Magento\Catalog\Block\Product\ListProduct
    {

      protected $_defaultToolbarBlock = Toolbar::class;

    /**
     * Product Collection
     *
     * @var AbstractCollection
     */
    protected $_productCollection;

    /**
     * Catalog layer
     *
     * @var Layer
     */
    protected $_catalogLayer;

    /**
     * @var PostHelper
     */
    protected $_postDataHelper;

    /**
     * @var Data
     */
    protected $urlHelper;
    protected $request;
    /**
     * @var CategoryRepositoryInterface
     */
    protected $categoryRepository;
    public function __construct(
        \Magento\Catalog\Block\Product\Context $context,
        PostHelper $postDataHelper,
        Resolver $layerResolver,
        CategoryRepositoryInterface $categoryRepository,
        Data $urlHelper,
        Http $request,
        array $data = []
    ) {
        $this->_catalogLayer = $layerResolver->get();
        $this->_postDataHelper = $postDataHelper;
        $this->categoryRepository = $categoryRepository;
        $this->urlHelper = $urlHelper;
        parent::__construct($context,$postDataHelper,$layerResolver,$categoryRepository,$urlHelper,$data);
    }


    public function initializeProductCollection(){
        echo "stringjhhj";
        echo $categoryId = $this->request->getParam('myselection'); // all params

            $layer = $this->getLayer();
        /* @var $layer Layer */
        if ($this->getShowRootCategory()) {
            $this->setCategoryId($this->_storeManager->getStore()->getRootCategoryId());
        }

        // if this is a product view page
        if ($this->_coreRegistry->registry('product')) {
            // get collection of categories this product is associated with
            $categories = $this->_coreRegistry->registry('product')
                ->getCategoryCollection()->setPage(1, 1)
                ->load();
            // if the product is associated with any category
            if ($categories->count()) {
                // show products from this category
                $this->setCategoryId(current($categories->getIterator())->getId());
            }
        }

        $origCategory = null;
        if ($this->getCategoryId()) {
            try {
             $category = $this->categoryRepository->get($this->getCategoryId());
             var_dump( $category);die;
            } catch (NoSuchEntityException $e) {
               echo $category = null;
            }

            if ($category) {
                $origCategory = $layer->getCurrentCategory();
                $layer->setCurrentCategory($category);
            }
        }
        $collection = $layer->getProductCollection();
        var_dump($collection->getData());

        $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());

        if ($origCategory) {
            $layer->setCurrentCategory($origCategory);
        }

        //$this->addToolbarBlock($collection);

        $this->_eventManager->dispatch(
            'catalog_block_product_list_collection',
            ['collection' => $collection]
        );

        return $collection;
    }

    public function  _getProductCollection(){
    // make changes here means call MyinitializeProductCollection in place of initializeProductCollection
            if ($this->_productCollection === null) {
            $this->_productCollection = $this->initializeProductCollection();
        }
        return $this->_productCollection;
    }

    public function getLoadedProductCollection(){
            // make changes here means call _MygetProductCollection in place of _getProductCollection
           // die("jhsjf");
        return $this->_getProductCollection();

    }
}

Finally run setup:upgrade, setup:di:compile and setup:static-content:deploy if needed and test.

5
  • [RuntimeException] Class Mageplaza\HelloWorld\Block\Rewrite\Product\Context does not exist Class Mageplaza\HelloWorld\Block\Rewrite\Product\ListProduct\Interceptor ge neration error: The requested class did not generate properly, because the 'generated' directory permission is read-only. If --- after running the 'bi n/magento setup:di:compile'
    – ragini
    Dec 28, 2018 at 5:00
  • as i am giving the permission but still it is not taking and give this error ,even i deleted both var and generated folder but not working
    – ragini
    Dec 28, 2018 at 5:01
  • Can you check my updated answer? Dec 28, 2018 at 8:04
  • yes it is problem of context
    – ragini
    Dec 28, 2018 at 8:18
  • Updated one not working? I have changed the context path? Dec 28, 2018 at 8:19

Your Answer

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

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