4

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.

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

1 Answer 1

4

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.

1
  • Problem solved by overriding \Magento\Quote\Model\Quote\Address class as it was inheriting \Magento\Customer\Model\Address\AbstractAddress.
    – MAK
    Jan 5, 2017 at 11:22

Your Answer

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

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