In this tutorial, We want to get all the items of the placed order.
The customer placed an order and after place order, if a developer needs to get all the items programmatically this tutorial will help them.
We can get all the items of the order by order id in Magento 2 by just simple code snippets. For, getting all the items of Order we need to required order id.
Using Modular Way, Proper Way for Development
Getting all the items of Order using Standard Magento way, By Creating the module,
Create Block file,
<?php namespace Rbj\OrderItems\Block; class Items extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Sales\Api\OrderRepositoryInterface $orderRepository, array $data = [] ) { $this->orderRepository = $orderRepository; parent::__construct($context, $data); } /* Load Order data by order_id */ public function getOrderData($order_id) { try { $order = $this->orderRepository->get($order_id); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { throw new \Magento\Framework\Exception\LocalizedException(__('This order no longer exists.')); } return $order; } }
Call function from Template(.phtml) file,
<?php $orderId = 10; // PASS_DYNAMIC_ORDER_ID $order = $block->getOrderData($orderId); foreach ($order->getAllVisibleItems() as $_item) { echo $_item->getId(); echo $_item->getSku(); echo $_item->getName(); echo $_item->getProductType(); echo $_item->getQtyOrdered(); echo "<pre>";print_r($_item->debug()); } ?>
You got a result of all the items of the specific order.
It’s really helpful. Thanks Rakesh …. !!!
Thanks for sharing Rakesh! 🙂
Thanks Rafeel.
@Yatin @Rafael Corrêa Gomes, Thanks for your kind words. I hope you like article.
Thanks for sharing this tutorial. Is there any other way to do it, rather than using object manager?
I have already mention Magento Module wah below the objectmanager. I have given demo using Block-template way.
Thanks for sharing this tutorial. Is there any other way to do it, rather than using object manager?
I have already mention Magento Module wah below the objectmanager. I have given demo using Block-template way.
It’s really helpful. Thanks Rakesh …. !!!
@Yatin @Rafael Corrêa Gomes, Thanks for your kind words. I hope you like article.
Thanks for sharing Rakesh! 🙂
Thanks Rafeel.