1

I am trying to inject my custom object in constructor like this in di.xml

<type name="Magento\CatalogSearch\Block\Advanced\Result">
    <arguments>
        <argument name="data" xsi:type="array">
            <item name="catalogFilterHelper" xsi:type="string">Package\Module\Helper\Data</item>
        </argument>
    </arguments>
</type>
<type name="Magento\CatalogSearch\Block\Result">
    <arguments>
        <argument name="data" xsi:type="array">
            <item name="catalogFilterHelper" xsi:type="object">Package\Module\Helper\Data</item>
        </argument>
    </arguments>
</type>

And trying to access it in theme template like app/design/frontend/Vendor/theme/Magento_CatalogSearch/templates/advanced/result.phtml

$block->getData('catalogFilterHelper');

It returns null.

When I am trying to get the object in the same template by using object manager.

//$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
//$block = $objectManager->get(\Magento\CatalogSearch\Block\Advanced\Result::class);

I get the proper result.

So seems like when layout is executed and blocks are created it overides the di.xml configurations for blocks $data array.

1 Answer 1

1

After some debugging I found out that Argument Replacement for Blocks using di.xml doesn't work. If the blocks are defined in layout.

The initialization of blocks in layout override the di.xml configuration.

To get it working I used the specific layout file and injected my object in layout block instead of di.xml. Which also called viewModel

<referenceBlock name="search.result">
        <arguments>
            <argument name="catalogFilterBlock" xsi:type="object">Package\Module\Helper\Data</argument>
        </arguments>
</referenceBlock>

And accessed it like this in the template

$catalogFilterHelper = $block->getData('catalogFilterBlock');

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.