Magento 2.1.3 Event Observer – Update Customer Custom Attribute Value

event-observermagento-2.1.3

I have created a custom attribute by the help of this link. Now I have to save/update value of this attribute in customer_save_before event observer.

Here is my observer.php code:

namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;

class RegisterUserOnCoop implements ObserverInterface
{
    /**
    * @var \Magento\Framework\App\ResponseFactory
    */
    protected $_customerRepositoryInterface;

    public function __construct(
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
    ) {
        $this->_customerRepositoryInterface = $customerRepositoryInterface;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $customerData = $observer->getEvent()->getCustomer();
        $customerData->setCustomAttribute('customer_attribute', $value);
        $this->_customerRepositoryInterface->save($customerData);
    }
}

Any help will be appreciated?

Best Answer

Finally, I find out solution for above problem. Posted answer for the helping purpose.

namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Customer;

class RegisterUserOnCoop implements ObserverInterface
{
    /**
    * @var \Magento\Framework\App\ResponseFactory
    */
    protected $_customerRepositoryInterface;

    public function __construct(
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
) {
        $this->_customerRepositoryInterface = $customerRepositoryInterface;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {   
        $customer = $observer->getEvent()->getCustomer();
        $customerData = $customer->getDataModel();
        $customerData->setCustomAttribute('customer_attribute', $value);
        $customer->updateData($customerData);
        $customer->save();
    }
}

Thanks!