In this post I am going to explain how to get shipment details by order id in Magento 2.
Using below code snippet you can get shipment details by passing order id.
1. Using Dependency Injection
Add below code snippet in Block class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | protected $_searchCriteriaBuilder; protected $_shipmentRepositoryInterface; protected $_logger; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder, \Magento\Sales\Api\ShipmentRepositoryInterface $shipmentRepositoryInterface, \Psr\Log\LoggerInterface $logger, array $data = [] ) { $this->_searchCriteriaBuilder = $searchCriteriaBuilder; $this->_shipmentRepositoryInterface = $shipmentRepositoryInterface; $this->_logger = $logger; parent::__construct($context, $data); } public function getShipmentDetails($orderId) { $shipmentData = array(); if($orderId > ) { $searchCriteria = $this->_searchCriteriaBuilder->addFilter('order_id', $orderId)->create(); try { $shipments = $this->_shipmentRepositoryInterface->getList($searchCriteria); $shipmentData = $shipments->getItems(); } catch (Exception $exception) { $this->_logger->critical($exception->getMessage()); $shipmentData = null; } } return $shipmentData; } |
Add below code snippet in template file.
1 2 3 4 5 6 7 8 9 10 11 12 | // Order Id $orderId = 1; $shipmentData = $block->getShipmentDetails($orderId); if ($shipmentData && count($shipmentData) > 0) { foreach ($shipmentData As $shipment) { echo "<pre>"; print_r($shipment->getData()); echo "</pre>"; } } |
2. Using Object Manager
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Order Id $orderId = 1; $shipmentRepositoryInterface = $objectManager->get('Magento\Sales\Api\ShipmentRepositoryInterface'); $searchCriteriaBuilder = $objectManager->get('Magento\Framework\Api\SearchCriteriaBuilder'); $logger = $objectManager->get('Psr\Log\LoggerInterface'); $searchCriteria = $searchCriteriaBuilder->addFilter('order_id', $orderId)->create(); try { $shipments = $shipmentRepositoryInterface->getList($searchCriteria); $shipmentData = $shipments->getItems(); } catch (Exception $exception) { $logger->critical($exception->getMessage()); $shipmentData = null; } if ($shipmentData && count($shipmentData) > 0) { foreach ($shipmentData As $shipment) { echo "<pre>"; print_r($shipment->getData()); echo "</pre>"; } } |
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!
Leave a Reply