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?

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

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

  • how do we get customer id here please reply me thanks – Nagaraju Kasa Nov 20 '17 at 11:32
  • @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 – Kaushal Suthar Jul 10 '18 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.