0

I need something to do using order item ids when order is created.

I tried sales_order_place_after and sales_order_save_after events, but unfortunately. Items from $observer->getEvent()->getOrder()->getAllVisibleItems() do not have Ids.

Which way should I go to achieve my needs? Also I need to avoid use of checkout controller events, because my code should work on the admin scope too.

2 Answers 2

4

After digging into ResourceModel\Order and AbstractModel classes I found event sales_order_save_commit_after and it works perfectly for me.

2
  • Thankyou man! Save my day Feb 11, 2022 at 12:52
  • Thank you @spiilmusic, it works as expected.
    – Rik Patel
    Feb 13, 2023 at 13:11
1

You can try this way. you don't need to inject order model

$order = $observer->getEvent()->getOrder();
$orderItems = $order->getAllItems();
foreach($orderItems ad $item){
 echo "Order Item ID :".$item->getItemId();
}

Let me know if it does not work for you.

Update Date:- 18th Aug, 2021 Magento ver: 2.4, & I tested in magento version version 2.4

$order = $observer->getEvent()->getOrder();
$orderId = $order->getId();
foreach($order->getAllVisibleItems() as $item ) {
   $productId = $item->getProductId();
   $QtyOrdered = $item->getQtyOrdered();
}

but we can't debug it in sales_order_save_after event using like echo $variable, print_r($variable) or echo "console.log(".json_encode($variable).")";

If you want to debug it then use logger method(print in log file).

See Below Example code

$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/templog.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('Catched event succssfully');

I hope this is helps to you... Thank you


Update Date :- 17th Oct, 2022

for use Logger Method in Magento version: 2.4.3+:

$writer = new \Zend_Log_Writer_Stream(BP . '/var/log/templog.log');
$logger = new \Zend_Log();
$logger->addWriter($writer);
$logger->info('Catched event succssfully');
1
  • No, It doesn't work. But I already found solution
    – spiilmusic
    Nov 9, 2018 at 10:44

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.