Magento 2 – Updating Custom Customer Attribute Programmatically

custom-attributescustomercustomer-attributemagento2

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

<?php
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');
        $this->_customerRepositoryInterface->save($customer);
        exit;

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

Best Answer

Use beforeSave Plugin. Using afterSave caused the infinite loop.