I am trying to extend the Magento\Catalog\Block\Product\ListProduct block in Magento 2.1 My Vendor_ModuleName module has the registration.php, the etc/module.xml and it's enabled.

Then I add an etc/di.xml file with the following content:

<?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\Product\ListProduct" type="Vendor\ModuleName\Block\Product\ListProduct" />

I expect the rendering of the catalog listing to break because my module block has not yet been created, however, my catalog seems to render as usual.

Indeed, no matter what I put in my Vendor\ModuleName\Block\Product\ListProduct class, it's completely ignored, and this is confirmed by enabling template and block name hints on the storefront: The output block is Magento\Catalog\Block\Product\ListProduct

What is it that I've missed here?

  • Is this a duplicate of magento.stackexchange.com/questions/138183/… ? – dmatthew Mar 20 '17 at 21:49
  • I tried adding your preference in di.xml file and I get the following error since I have not created that class: 2 exception(s): Exception #0 (Magento\Framework\Exception\LocalizedException): Invalid block type: Magento\Catalog\Block\Product\ListProduct Exception #1 (ReflectionException): Class Vendor\ModuleName\Block\Product\ListProduct does not exist – dmatthew Mar 20 '17 at 21:51

I believe you have your preference reversed. The type attribute is the base class you want to override, and the for attribute is the class you want to render instead of the type.

So in your case, try:

<?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="Vendor\ModuleName\Block\Product\ListProduct" type="Magento\Catalog\Block\Product\ListProduct" />

This is wrong, I was confused.

| improve this answer | |
  • I tried to reverse it, but still no effect. However, your suggestion seems contrary to the documentation I've seen so far: type should be my extension and for the core class that I want to extend, right? – kyegil Mar 20 '17 at 18:18
  • You are clearing your cache after making configuration changes correct? – Brett Mar 20 '17 at 18:20
  • yes, cleared and reindexed – kyegil Mar 20 '17 at 18:23
  • This is incorrect, The "for" is the class you want to override, and the "type" is the class which is doing the overriding. – dmatthew Mar 20 '17 at 21:41

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.