2

I want to override the function getLabelHtml in Magento\Framework\Data\Form\Element\AbstractElement.php

I make a copy of this file in my \app\code\CompanyName\ModuleName\Model\Framework\Data\Form\Element\AbstractElement.php

and I create a file in \app\code\CompanyName\ModuleName\etc\adminhtml\di.xml with this code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Magento\Framework\Data\Form\Element\AbstractElement" type="CompanyName\ModuleName\Model\Framework\Data\Form\Element\AbstractElement"/>
</config>

and then I compile the module. But is not work. Not override.

1

Same as on Magento 1, you cannot rewrite abstract classes.
The class you are trying to rewrite is an abstract class.
The preferences you declare in di.xml are used only when instantiating classes that have other classes as dependencies.
In you case, in case there is a class that has a dependency an instance of Magento\Framework\Data\Form\Element\AbstractElement it will work, but most probably there are no such classes.

Even if you declare a preference for the abstract class, the classes that extend the abstract class will still extend the original class, not yours.
I think the way to go on this case is to create a before|after|around plugin for the method getLabelHtml for your abstract class

  • You can also write plugins for abstract classes. – Fabian Schmengler Jun 16 '16 at 8:53
  • @fschmengler. I wasn't sure about that. Thanks for clearing it. – Marius Jun 16 '16 at 8:55
  • Do you have any example how to create it and rewrite the function getLabelHtml? – THKAN Jun 16 '16 at 15:42

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