2

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.

1 Answer 1

1

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

4
  • 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, 2016 at 2:45
  • @TylerBean there's definitely an issue here. Does Module 2 depends on Module 1 ? Aug 26, 2016 at 6:54
  • I have 2 ChildBlock, one of them doesn't override __construct method. Is it the cause?
    – Tyler Bean
    Aug 31, 2016 at 4:04
  • @TylerBean I'm not sure to be honest Aug 31, 2016 at 6:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.