Creating an shipment is very easy, as developer we have to use Core converter of order objects.
Create full shipment using below code.
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 86 |
<?php namespace CWM\Shipment\Controller\Order; class CreateShipment extends Magento\Framework\App\Action\Action { /** * @var \Magento\Sales\Api\OrderRepositoryInterface */ protected $_orderRepository; /** * @var \Magento\Sales\Model\Convert\Order */ protected $_convertOrder; /** * @var \Magento\Shipping\Model\ShipmentNotifier */ protected $_shipmentNotifier; /** * @param Context $context * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository * @param \Magento\Sales\Model\Convert\Order $convertOrder * @param \Magento\Shipping\Model\ShipmentNotifier $shipmentNotifier */ public function __construct( Context $context, \Magento\Sales\Api\OrderRepositoryInterface $orderRepository, \Magento\Sales\Model\Convert\Order $convertOrder, \Magento\Shipping\Model\ShipmentNotifier $shipmentNotifier ) { $this->_orderRepository = $orderRepository; $this->_convertOrder = $convertOrder; $this->_shipmentNotifier = $shipmentNotifier; parent::__construct($context); } /** * Create Shipment Controller */ public function execute() { $orderId = 12; $order = $this->_orderRepository->get($orderId); // to check order can ship or not if (!$order->canShip()) { throw new \Magento\Framework\Exception\LocalizedException( __("You can't create the Shipment of this order.") ); } $orderShipment = $this->_convertOrder->toShipment($order); foreach ($order->getAllItems() AS $orderItem) { // Check virtual item and item Quantity if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) { continue; } $qty = $orderItem->getQtyToShip(); $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qty); $orderShipment->addItem($shipmentItem); } $orderShipment->register(); $orderShipment->getOrder()->setIsInProcess(true); try { // Save created Order Shipment $orderShipment->save(); $orderShipment->getOrder()->save(); // Send Shipment Email $this->_shipmentNotifier->notify($orderShipment); $orderShipment->save(); } catch (\Exception $e) { throw new \Magento\Framework\Exception\LocalizedException( __($e->getMessage()) ); } } } |