PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 23, 2022

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

 August 23, 2022     magento2, observers, php     No comments   

Issue

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 \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $orderInstance = $observer->getEvent()->getdata();
        $orderIds = $observer->getEvent()->getdata('order_ids');
        $orderCount = is_array($orderIds)?count($orderIds):0;
        $orderId = current($orderIds);
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $session = $objectManager->get('Magento\Customer\Model\Session');

        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


Solution

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

$customerResourceModel->save($customer);


Answered By - Reggie Te
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing