0

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?

4
  • Please share your observer code Commented Jan 11, 2017 at 6:10
  • Right now i have no observer code i have done it with override createpost controller Commented Jan 11, 2017 at 6:12
  • You have mentioned that "I have also used customer save after" that's whay i have asked Commented Jan 11, 2017 at 6:14
  • Yes I have tried it but at that time it was not working so i used second solution by override controller Commented Jan 11, 2017 at 6:30

1 Answer 1

8

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

2
  • how do we get customer id here please reply me thanks Commented Nov 20, 2017 at 11:32
  • 1
    @SohelRana: PHP Fatal error: Uncaught TypeError: Argument 1 passed to Magento\Customer\Model\ResourceModel\CustomerRepository\Interceptor::save() must implement interface Magento\Customer\Api\Data\CustomerInterface Commented Jul 10, 2018 at 13:08

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.