In this article, we are going to understand How to Save Custom Attribute Value After Customer Register Successful in Magento 2. Previously, we have learned about how to add customer attribute programmatically in magento2. Now let’s see:
Steps to save customer attribute in Magento2:
Step 1:
Firstly, create app\code\Webiators\CustomerAttribute\etc\events.xml
1 2 3 4 5 6 7 8 9 10 11 |
<?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="event_customer_register_success" instance="Webiators\CustomerAttribute\Observer\Customer\RegisterSuccessObserver" /> </event> </config> |
Step 2:
Now create, app\code\Webiators\CustomerAttribute\ Observer\Customer\RegisterSuccessObserver.php file and add this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<?php namespace Webiators\CustomerAttribute\Observer\Customer; use Magento\Framework\Event\ObserverInterface; use Magento\Customer\Api\CustomerRepositoryInterface; class RegisterSuccessObserver implements ObserverInterface { protected $customerRepository; public function __construct( CustomerRepositoryInterface $customerRepository) { $this->customerRepository = $customerRepository; } public function execute(\Magento\Framework\Event\Observer $observer) { $customer = $observer->getEvent()->getCustomer(); $customer->setCustomAttribute('magento_username', 'Test'); $this->customerRepository->save($customer); return $this; } } |
In this above code, we have set customer attribute name as ‘magento_username‘ and value as ‘Test‘.
That’s it!
If you have any issues in this topic feel free to mention them in the comment section below.
Thank you.