Skip to content

Instantly share code, notes, and snippets.

@kanduvisla
Created November 8, 2016 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanduvisla/d56349426ee077dbf08893e88a264393 to your computer and use it in GitHub Desktop.
Save kanduvisla/d56349426ee077dbf08893e88a264393 to your computer and use it in GitHub Desktop.
Magento 2 : Create shipment from order:
/**
* @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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment