Magento – How to override Virtual Type class in Magento 2

blocksdependency-injectionmagento2moduleoverrides

How to override VirtualType block in Magento 2, I want to override following virtual type block with my own block,

<virtualType name="Magento\CatalogSearch\Block\SearchResult\ListProduct" type="Magento\Catalog\Block\Product\ListProduct">
   <arguments>
       <argument name="catalogLayer" xsi:type="object">Magento\Catalog\Model\Layer\Search</argument>
   </arguments>
</virtualType>

So I tried to override it from my custom module di.xml like this,

<preference for="Magento\Catalog\Block\Product\ListProduct" type="My\Vendor\Block\Product\ListProductSearch" />

But it does not work.

So, what is the proper way of overriding a virtual type class in Magento 2?

Best Answer

You have to use:

<preference for="Magento\CatalogSearch\Block\SearchResult\ListProduct" type="Vendor\Module\Block\Product\ListProductSearch" />

as Raphael mentioned.

To make this singular block working properly, you need also to add view/frontend/layout/catalogsearch_result_index.xml file with following content:

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceBlock name="search_result_list">
        <action method="setTemplate">
            <argument name="template" xsi:type="string">Magento_Catalog::product/list.phtml</argument>
        </action>
    </referenceBlock>
</body>

Related Topic