I'm working on a module in Magento 2.1 and have to override validate function of this class Magento\Customer\Model\Address
This is what my di.xml contains:
<?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\Customer\Model\Address\AbstractAddress" type="Mymodule\Module\Model\Address\AbstractAddress" />
</config>
and this is what my file contains:
<?php
namespace Mymodule\Module\Model\Address;
class AbstractAddress extends \Magento\Customer\Model\Address\AbstractAddress
{
public function validate()
{
$errors = [];
if (!\Zend_Validate::is($this->getFirstname(), 'NotEmpty')) {
$errors[] = __('Please enter the first name and last name.');
}
return parent::validate();
}
}
But I'm still not able to override the model.
Best Answer
You cannot override classes which does not injected via DI. This class used only as parent and does not injected in any contructors and does not created via
ObjectManager
.To override this model you need to create preference on injected subtypes (
\Magento\Customer\Model\Address
, ...).But preference is not good way to add functionality. You can write plugin on
\Magento\Customer\Model\Address\AbstractAddress
and easy solve your problem.