I am trying to update a custom customer attribute, I have the following code

namespace Vendor\Module\Plugin;

use Magento\Customer\Model\ResourceModel\CustomerRepository;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Model\CustomerFactory;

class CustomerAfterSave
    protected $_customerDataFactory;
    protected $_customerRepositoryInterface;
    protected $_customerRepository;

    public function __construct(
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
    ) {

        $this->_customerRepositoryInterface = $customerRepositoryInterface;
        $this->_customerFactory = $customerFactory;

    public function afterSave(CustomerRepository $subject,$savedCustomer)
        //Get Customer
        $customerId = $savedCustomer->getId();

        $customer = $this->_customerRepositoryInterface->getById($customerId);
        $customer->setCustomAttribute('my_custom_attribute', 'test');

But then I get the following error

( ! ) Fatal error: Maximum function nesting level of '256' reached, aborting! in /vendor/magento/module-customer/Model/ResourceModel/Address.php on line 58

Could anyone advise and see where I am going wrong

Edit: I don't believe this to be a duplicate question as I have disabled xdebug and the code just times out

Further edit: I think my problem is the same as Magento 2 : How to save data in database

  • I think it's a different case. It doesn't duplicate. – Khoa TruongDinh Dec 20 '17 at 8:44

Use beforeSave Plugin. Using afterSave caused the infinite loop.

  • I need to use afterSave as I need to customer id for newly inserted customers to pass to a 3rd party system – Goose84 Dec 18 '17 at 15:22
  • Why do you need to save the customer itself again? – Khoa TruongDinh Dec 18 '17 at 15:25
  • When a customer is created I need to submit their data to a 3rd party. The data I submit is the newly created customer id and then when the 3rd party system responses I then need to update the custom customer attribute – Goose84 Dec 18 '17 at 15:55
  • So, from the 3rd party system, is there existing customer info or not? I have an idea for you. Before saving customer info on the Magento side, we need to get the info from the 3rd system, and then compare with current customer info on the Magento side. Finally, save the customer info. – Khoa TruongDinh Dec 18 '17 at 16:02
  • Unfortunately not, I need the customer to be saved in Magento first then in the 3rd party system – Goose84 Dec 18 '17 at 18:01

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.