0

I'm using Magento 2.3.4 and tried to catch the data order using sales_order_save_after observer like this:

etc/events.xml

<event name="sales_order_save_after">
    <observer instance="Vendor\Module\Observer\Sales\OrderSaveAfter" name="vendor_module_observer_sales_ordersaveafter_sales_order_save_after"/>
</event>

Vendor\Module\Observer\Sales\OrderSaveAfter

public function execute(
    \Magento\Framework\Event\Observer $observer
) { 
  $order = $observer->getEvent()->getOrder();
  if ($order && $order->getId()){
    $origState = $order->getOrigData('state');
    $curState = $order->getData('state');
    $oldStatus = $order->getOrigData('status');
    $newStatus = $order->getStatus();

    $this->_helper->customLog('OrderSaveAfter Observer', 'test.log');
    $stateLog = 'origState: '.$origState.';'.'curState: '.$curState;
    $statusLog = 'origStatus: '.$oldStatus.';'.'curStatus: '.$newStatus;
    $this->_helper->customLog('State Log => '.$stateLog, 'test.log');
    $this->_helper->customLog('Status Log => '.$statusLog, 'test.log');
  }
  return $this;
}

but i noticed , it logs the same things twice after place an order, is there a way to prevent this?

1
  • have you found any solution? Mar 26, 2021 at 9:48

1 Answer 1

0

Try this in your Observer file:

//Your code ........
protected $registry;
//Your code ........

public function __construct(
    .........
    \Magento\Framework\Registry $registry,
    .........
) {
    ........
    $this->registry = $registry;
    ........
}

public function execute(
    \Magento\Framework\Event\Observer $observer
) { 
    $registeryObserverCheck = $this->registry->registry('registeryObserverCheck');
    if(!$registeryObserverCheck) {
        $order = $observer->getEvent()->getOrder();
        if ($order && $order->getId()){
            $origState = $order->getOrigData('state');
            $curState = $order->getData('state');
            $oldStatus = $order->getOrigData('status');
            $newStatus = $order->getStatus();

            $this->_helper->customLog('OrderSaveAfter Observer', 'test.log');
            $stateLog = 'origState: '.$origState.';'.'curState: '.$curState;
            $statusLog = 'origStatus: '.$oldStatus.';'.'curStatus: '.$newStatus;
            $this->_helper->customLog('State Log => '.$stateLog, 'test.log');
            $this->_helper->customLog('Status Log => '.$statusLog, 'test.log');
        }
        $this->registry->register('registeryObserverCheck', true);
        return $this;
    }
}

Your Answer

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

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