How can I update customer custom attribute on order save?
-
18-03-2021 - |
Question
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?
Solution
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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange