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; } 

2 Answers 2

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

1
  • 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. Commented Mar 22, 2018 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(); } } 
1
  • 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. Commented Mar 22, 2018 at 21:03

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.