Magento 2 – Save Customer Attribute Value During Registration

customer-attributeevent-observermagento-2.1plugin

I have created one 'test' text customer attribute. I have added input field on frontend customer register form. I can able to save this attribute value by override createPost.php from my custom module.

But I think this is not proper way to save value by override controller. There is any way to save customer attribute using plugin or observer?

Best Answer

You can do this by observer.

SR/StackExchange/etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="customer_register_success">
        <observer name="sr_customer_account_createPost" instance="SR\StackExchange\Observer\CustomerRegisterSuccess" />
    </event>
</config>

SR/StackExchange/Observer/CustomerRegisterSuccess.php

namespace SR\StackExchange\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Customer\Api\CustomerRepositoryInterface;

class CustomerRegisterSuccess implements ObserverInterface
{
    /** @var CustomerRepositoryInterface */
    protected $customerRepository;

    /**
     * @param CustomerRepositoryInterface $customerRepository
     */
    public function __construct(
        CustomerRepositoryInterface $customerRepository
    ) {
        $this->customerRepository = $customerRepository;
    }

    /**
     * Manages redirect
     */
    public function execute(Observer $observer)
    {
        $accountController = $observer->getAccountController();
        $customer = $observer->getCustomer();
        $request = $accountController->getRequest();
        $customer_number = $request->getParam('customer_number');
        $customer->setCustomAttribute('customer_number', $customer_number);
        $this->customerRepository->save($customer);
    }
}

NB: here 'customer_number' is custom attribute

Related Topic