Originally: There are 2 blocks like this:

namespace Vendor\Module_1\Block;
class ParentBlock{}
class ChildBlock extends ParentBlock {}

Now, I need to rewrite ParentBlock using di.xml:

<preference for="Vendor\Module_1\Block\ParentBlock" type="Vendor\Module_2\Block\ParentBlock" />

namespace Vendor\Module_2\Block;
class ParentBlock extends \Vendor\Module_1\Block\ParentBlock {}

How can I make \Vendor\Module_1\Block\ChildBlock extend from \Vendor\Module_2\Block\ParentBlock?

If there is any more information needed, please tell me.

Thanks in advanced.


Updated following answers from @Raphael at Digital Pianism.

Thanks for your explanation. And I thought as you said too, but in my case, it doesn't work.

I have to create a new preference for Module_1\ChildBlock. Then I have to create new Module_2\ChildBlock like this:

namespace Vendor\Module_2\Block;
class ChildBlock extends \Vendor\Module_2\Block\ParentBlock {}

Finally, I have to copy all methods from Module_1\ChildBlock to this one.

This is so crazy!!! I don't know what's wrong, as well as how to fix this problem.


The preference will do everything you need for you.

A simplified definition of defining preferences for some classes could be that the new classes will be used instead of the old ones.

So in your case, as you defined a preference for the ParentBlock class, the ChildBlock will automatically extend the new ParentBlock class thanks to your preference

To summarize, everytime Magento 2 is supposed to instantiate Module_1\ParentBlock it will actually instantiate Module_2\ParentBlock instead

  • Please check my update above and discuss this. I think that there would be the case that the ChildBlock is still actually extended from Module_1\ParentBlock, despite the preference we use. – Tyler Bean Aug 26 '16 at 2:45
  • @TylerBean there's definitely an issue here. Does Module 2 depends on Module 1 ? – Raphael at Digital Pianism Aug 26 '16 at 6:54
  • I have 2 ChildBlock, one of them doesn't override __construct method. Is it the cause? – Tyler Bean Aug 31 '16 at 4:04
  • @TylerBean I'm not sure to be honest – Raphael at Digital Pianism Aug 31 '16 at 6:24

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.