Magento2 Module Dependencies – How to Add Dependencies When Rewriting a Module

magento2

I am trying to rewrite the \Magento\Catalog\Model\Layer\Filter\Item class in Magento by adding the following line to my di.xml:

<preference for="Magento\Catalog\Model\Layer\Filter\Item"
            type="Vendor\Module\Rewrite\Magento\Catalog\Model\Layer\Filter\Item"/>

Magento takes my Vendor\Module-class over it's default class, but I need to add some dependencies to it. Now I tried to add them by adjusting the __construct()-method and adding them there, but this doesn't work (which makes sence of course, because it breaks the chain for classes that try to extend the Item-object itself:

public function __construct(
    \Vendor\Module\Helper\Data $dataHelper,
    \Magento\Framework\UrlInterface $url,
    \Magento\Theme\Block\Html\Pager $htmlPagerBlock,
    array $data
) {
    $this->dataHelper = $dataHelper;
    parent::__construct($url, $htmlPagerBlock, $data);
}

The error I get is the following:

Missing required argument $data of Vendor\Module\Rewrite\Magento\Catalog\Model\Layer\Filter\Item.

So what's the proper way to get my helper in my rewritten object?

Best Answer

What you have done is correct but you have made the final $data argument required by not adding = [] after it as a default value.

Simply change array $data to array $data = [].

You may also have to clear the var/generation folder because you have changed the constructor params.

Related Topic