Skip to content
Advertisement

How can i save custom field value in customer_entity table in Magento 2 using observer

Below is my observer code:

<?php

class CustomerOrderCountObserver implements ObserverInterface
{

    /**
     * @var customerFactory
     */
    private $customerFactory;

    /**
     * 
     * @param CustomerFactory $customerFactory
     */
    public function __construct(
        CustomerFactory $customerFactory
    ) {
          $this->customerFactory = $customerFactory;
    }

    /**
     * Upgrade customer password hash when customer has logged in
     *
     * @param MagentoFrameworkEventObserver $observer
     * @return void
     */
    public function execute(MagentoFrameworkEventObserver $observer)
    {
        $orderInstance = $observer->getEvent()->getdata();
        $orderIds = $observer->getEvent()->getdata('order_ids');
        $orderCount = is_array($orderIds)?count($orderIds):0;
        $orderId = current($orderIds);
        $objectManager = MagentoFrameworkAppObjectManager::getInstance();
        $session = $objectManager->get('MagentoCustomerModelSession');

        if($session->isLoggedIn()) {
            $customer = $this->customerFactory->create()->load($session->getCustomerId());
            $orderCount = $orderCount + $customer->getOrderCount();
            $customer->setOrderCount($orderCount);
            $customer->save($customer);
        } 
    }
}

I don’t know what I am doing wrong with this. It is not saving the customer column value order_count

Advertisement

Answer

Try saving using the customer data changes using a resourceModel instead of saving using the model

$customerResourceModel->save($customer);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement