0

I've used sales_order_place_after to get order id after order placed from backend but it doesnt return order id. Not sure what's missing here.

Here's my observer

public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $order = $observer->getOrder();
        echo $orderId = $order->getId();  exit;
    }

Above code executed but if it doesnt print order id.

Any suggestions for this ? For all those who are curious I need to store order data after order plaed into custom table.

  • make sure you place events.xml under etc/adminhtml – Arunprabakaran M Aug 2 at 9:57
  • have you solved your problem? – Ketan Borada Aug 10 at 8:50
  • Yes I was able to solve issue. – Vivek Aug 12 at 4:51
0

You need to just change your code like this.

public function execute(\Magento\Framework\Event\Observer $observer)
{
        $order = $observer->getEvent()->getOrder();
        echo $orderId = $order->getId();  
        exit;
}
  • Its not working cant able to get order id error is "An ID is needed. Set the ID and try again." – Vivek Aug 2 at 10:38
0

add observer only for admin app\code\Vendor\Module\etc\adminhtml\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="load_custom_handler" instance="Vendor\Module\Observer\GetOrder" />
        </event>
    </config>

add observer file app\code\Vendor\Module\Observer\GetOrder.php

<?php 
namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;

class GetOrder implements ObserverInterface
{
    protected $orderFactory;

    public function __construct(\Magento\Sales\Model\Order $orderFactory)
    {
        $this->orderFactory = $orderFactory;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {

        $orderIds = $observer->getEvent()->getOrderIds();
        $orderId= $orderIds[0]; //Do your logic here

        $order = $this->orderFactory->load($orderId);
    }
}
  • Its not working cant able to get order id error is "An ID is needed. Set the ID and try again." – Vivek Aug 2 at 10:37
  • i've updated my answer – Ketan Borada Aug 2 at 10:58

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.