Magento2: Failed Override Magento_Tax module Class with protected method
-
15-04-2021 - |
Question
I am trying to override class Magento\Tax\Model\Sales\Total\Quote\CommonTaxCollector
I tried everything and checked the implementation is correct in di.xml
The method I am trying to override is a protected method processProductItems()
I have no clue what am I doing wrong here. It keeps calling the function from the original Magento_Tax class
di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Tax\Model\Sales\Total\Quote\CommonTaxCollector"
type="Folio3\TaxCollector\Model\Sales\Total\Quote\CommonTaxCollector"/>
</config>
Override class Folio3\TaxCollector\Model\Sales\Total\Quote\CommonTaxCollector.php
class CommonTaxCollector extends \Magento\Tax\Model\Sales\Total\Quote\CommonTaxCollector
{
...
module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Folio3_TaxCollector" setup_version="1.0.0">
<sequence>
<module name="Magento_Catalog"/>
<module name="Magento_Checkout"/>
<module name="Magento_Customer"/>
<module name="Magento_Directory"/>
<module name="Magento_User"/>
<module name="Magento_Tax" />
</sequence>
</module>
</config>
Can anyone explain to me what am I doing wrong here? I think I have followed all the necessary steps. It keeps calling the original CommonTaxCollector.php class from Magento_Tax module
Solution
This is because you are overriding the wrong class.
Magento\Tax\Model\Sales\Total\Quote\CommonTaxCollector
The class CommonTaxCollector is not used directly, Magento2 used a Tax class which overrides the CommonTaxCollector class.
vendor/magento/module-tax/Model/Sales/Total/Quote/Tax.php
Tax.php
namespace Magento\Tax\Model\Sales\Total\Quote;
....
class Tax extends CommonTaxCollector {
Solution:
di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Tax\Model\Sales\Total\Quote\Tax"
type="Folio3\TaxCollector\Model\Sales\Total\Quote\Tax"/>
</config>
Override class Folio3\TaxCollector\Model\Sales\Total\Quote\Tax.php
class Tax extends \Magento\Tax\Model\Sales\Total\Quote\Tax
{
...
It should work fine!