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" />

and this is what my file contains:


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.

  • are you refresh cache. – xanka Jan 5 '17 at 11:01
  • @MAK,how to overriding \Magento\Quote\Model\Quote\Address? – ben May 8 '18 at 7:36

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.

| improve this answer | |
  • Problem solved by overriding \Magento\Quote\Model\Quote\Address class as it was inheriting \Magento\Customer\Model\Address\AbstractAddress. – MAK Jan 5 '17 at 11:22

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.