How to Create Shipment Programmatically in Magento 2. If we need to programmatically create shipment for an order then you can create by following way.
For automation Magento, we required auto-create a shipment, so I decided to write this post for creating shipment by code so after placing an order it will auto-generate shipment.
Following are the steps to create a shipment.
Related post: Top 10 Best Magento shipping extensions 2018 (Free & Premium)
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 |
// Load the order $order = $this->_objectManager->create('Magento\Sales\Model\Order') ->loadByAttribute('increment_id', '000000001'); OR $order = $this->_objectManager->create('Magento\Sales\Model\Order') ->load('1'); // Check if order can be shipped or has already shipped if (! $order->canShip()) { throw new \Magento\Framework\Exception\LocalizedException( __('You can\'t create an shipment.') ); } // Initialize the order shipment object $convertOrder = $this->_objectManager->create('Magento\Sales\Model\Convert\Order'); $shipment = $convertOrder->toShipment($order); // Loop through order items foreach ($order->getAllItems() AS $orderItem) { // Check if order item has qty to ship or is virtual if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) { continue; } $qtyShipped = $orderItem->getQtyToShip(); // Create shipment item with qty $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped); // Add shipment item to shipment $shipment->addItem($shipmentItem); } // Register shipment $shipment->register(); $shipment->getOrder()->setIsInProcess(true); try { // Save created shipment and order $shipment->save(); $shipment->getOrder()->save(); // Send email $this->_objectManager->create('Magento\Shipping\Model\ShipmentNotifier') ->notify($shipment); $shipment->save(); } catch (\Exception $e) { throw new \Magento\Framework\Exception\LocalizedException( __($e->getMessage()) ); } |
The steps I mention above is the shortest process for you to create Shipment Programmatically in Magento 2.
Thank you for reading this post and see you in other posts from Magestore!