2

I have an observer for the event when an order is placed by a customer. I tried "sales_model_service_quote_submit_before"

I would like to take a value from the Order and save it to the customer.

For example.

$customer = $quote->getCustomer();
if ($customer) {
  $customer->setData('someValue', $quote->getData('someValue')))
  $customer->save();
}

I have also tried

$customerId = $quote->getCustomerId();
if ($customerId) {
  $customer = $customerRepository->getById($customerId);
  $customer->setSomeValue('1234');
  $customer->save();
}

Can someone please provide an example of an observer to do this correctly?

1 Answer 1

2

Try This :-

protected $_customerRepositoryInterface;

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

public function execute()
{
    $customerId = 2; // Corresponding customer id
    $customer = $this->_customerFactory->create()->load($customerId)->getDataModel();
    $customer->setCustomAttribute('custom_attribute_name', 'value');
    $this->_customerRepositoryInterface->save($customer);
}
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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