2

I'm trying to get order data (order id for now) from an observer using the event sales_order_place_after.

The event fires and does not get any errors, but my order_id is blank. Any help as to why this isn't working as I expect?

My 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="sales_order_place_after">
        <observer name="PingOnSale" instance="Vendor\Module\Observer\PingOnSale" />
    </event>
</config>

My Observer

namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;

class PingOnSale implements ObserverInterface
{
    /**
     * @param \Magento\Framework\Event\Observer $observer
     * @return bool
     */
    public function execute(\Magento\Framework\Event\Observer $observer){
        $order = $observer->getData('order');
        $order_id = $order->getId(); 
        // $order_id is blank when logging to file
        return true;
    }
}

I have also tried this method, that is the accepted answer from the question which did not work. According to the documentation, $observer->getData(); is the right way to do this.

The event dispatches from Magento\Sales\Model\Order and as far as I can tell my code should be getting the order. Here is the relevant code from the Order class.

public function place()
{
    $this->_eventManager->dispatch('sales_order_place_before', ['order' => $this]);
    $this->_placePayment();
    $this->_eventManager->dispatch('sales_order_place_after', ['order' => $this]);
    return $this;
}
1

With the event sales_order_save_after the order hasn't been committed to the Database yet.

Using the event checkout_submit_all_after or checkout_onepage_controller_success_action should let you grab the order id

  • I've accepted your answer. Thanks for explaining why it wasn't working and providing the event I was looking for. So far checkout_submit_all_after seems to be what I needed. – jamil Mar 22 '18 at 21:01
2

You can get order id in observer, using $observer->getEvent()->getOrderIds();. which you can use in your execute function like this :

<?php

public function execute(\Magento\Framework\Event\Observer $observer)
{      
    $orderids = $observer->getEvent()->getOrderIds();
    foreach($orderids as $orderid){
        $order = $this->_order->load($orderid);

       // Get Payment method
       $payment_method_code = $order->getPayment()->getMethodInstance()->getCode();             
    }

}
  • Thanks for the response, I didn't get a chance to test your answer because I think the best solution for me is to use a different event, as another user suggested. – jamil Mar 22 '18 at 21:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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