I’ve recently found a small article on how to convert an order to a shipment in Magento 2, but the code in question was a bit outdated.
For example, it leaned heavily on the Object Manager instead of handling it with dependency injection and repositories.
For that reason, I rewrote the code a bit to make it more compatible with Magento 2.1.x:
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
<?php use Magento\Framework\Exception\LocalizedException; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Sales\Api\ShipmentRepositoryInterface; /** * Class OrderToShipment */ class OrderToShipment { /** * @var OrderRepositoryInterface */ protected $orderRepository; /** * @var \Magento\Sales\Model\Convert\Order */ protected $convertOrder; /** * @var ShipmentRepositoryInterface */ protected $shipmentRepository; /** * Order constructor. * @param OrderRepositoryInterface $orderRepository * @param ShipmentRepositoryInterface $shipmentRepository * @param \Magento\Sales\Model\Convert\Order $convertOrder */ public function __construct( OrderRepositoryInterface $orderRepository, ShipmentRepositoryInterface $shipmentRepository, \Magento\Sales\Model\Convert\Order $convertOrder ) { $this->orderRepository = $orderRepository; $this->shipmentRepository = $shipmentRepository; $this->convertOrder = $convertOrder; } /** * @param int $orderId * @return \Magento\Sales\Model\Order\Shipment * @throws LocalizedException */ public function createShipmentFromOrderId(int $orderId) { /** @var \Magento\Sales\Model\Order $order */ $order = $this->orderRepository->get($orderId); if (!$order->canShip()) { throw new LocalizedException(__('Order cannot be shipped.')); } // Create the shipment: $shipment = $this->convertOrder->toShipment($order); // Add items to shipment: foreach ($order->getAllItems() as $orderItem) { if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) { continue; } $qtyShipped = $orderItem->getQtyToShip(); $shipmentItem = $this->convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped); $shipment->addItem($shipmentItem); } // Register the shipment: $shipment->register(); try { $this->shipmentRepository->save($shipment); $this->orderRepository->save($shipment->getOrder()); } catch (\Exception $e) { throw new LocalizedException(__($e->getMessage())); } return $shipment; } } |
Visitors give this article an average rating of 4.0 out of 5.
How would you rate this article?
★ ★ ★ ★ ★
Great Article, but I think one thing is missing. How can you notify the customer about the new shipment?