Skip to main content
3 of 3
added 2 characters in body
Purushotam Sharma
  • 1.7k
  • 2
  • 26
  • 60

Magento 2: not able to get order details in observer

I am not able to get order details in observer using sales_order_save_before event:-

Path: - /app/code/Company/Mymodule/etc/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_category_delete_after">
        <observer name="Mymodule" instance="Company\Mymodule\Observer\Onafterdelete"/>
    </event>
    <event name="sales_order_save_before">
        <observer name="Mymodule" instance="Company\Mymodule\Observer\Onbeforesaveorder"/>
    </event>
</config>

Path:- /app/code/Company/Mymodule/Observer/Onbeforesaveorder.php <?php namespace Company\Mymodule\Observer;

class Onbeforesaveorder implements \Magento\Framework\Event\ObserverInterface
{
    protected $_resource;

    /**
    * @var \Psr\Log\LoggerInterface
    */
   protected $_logger;  
    
    public function __construct(
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\App\ResourceConnection $resource
    ) {
        $this->_logger = $logger;
        $this->_resource = $resource;
    }  
  
  public function execute(\Magento\Framework\Event\Observer $observer)
  {
    $orderObj = $observer->getOrder();
    $order = $observer->getEvent()->getOrder();
    
    if($order->getId()){
        $this->_logger->debug($order->getEntityId()." observer1111");
    }
    
    if ($orderObj->getId()){
        $this->_logger->debug($orderObj->getEntityId()." observer22222");
    }
    
    $this->_logger->debug("observer3333");// event is fired because I am getting this message in my log file.
    return $this;
  }
}

I am trying two way to get order ID in my code but both way is not working.

Please let me know if I am missing any thing or doing wrong as event is fired but not able to get order details in observer.

Purushotam Sharma
  • 1.7k
  • 2
  • 26
  • 60