Create shipment programmatically in Magento2

The below code script will create order shipment programmatically after placing order. This is useful if you want to automate the shipment process. You can achieve this by calling order success event.

 

[php]
<?php namespace Vendor\Module\Controller; class OrderShipment extends Magento\Framework\App\Action\Action{ /** * @var \Magento\Framework\App\ObjectManager */ protected $_objectManager; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\App\ObjectManager ) { $this->_objectManager
parent::__construct($context);
}
/**
* order shipment controller.
*
* @return \Magento\Framework\View\Result\Page
*/
public function execute()
{

// get order Id and load order object
$order = $this->_objectManager->create(‘Magento\Sales\Model\Order’)->load(‘1’);

// Check if order is availabel for shipped or has shipped already
if (! $order->canShip()) {
throw new \Magento\Framework\Exception\LocalizedException(__(‘You can not create shipment for this order.’));
}

// Initiate the order shipment
$convertOrder = $this->_objectManager->create(‘Magento\Sales\Model\Convert\Order’);
$shipment = $convertOrder->toShipment($order);

// Check all order items
foreach ($order->getAllItems() AS $orderItem) {
// Check if order item is virtual or has quantity for shipment
if (! $orderItem->getIsVirtual() || $orderItem->getQtyToShip()) {
continue;
}

$qtyShipped = $orderItem->getQtyToShip();

// Create shipment with order item qty
$shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);

// Add $shipmentItem to shipment
$shipment->addItem($shipmentItem);
}

// Register shipment and set status as processing
$shipment->register();

$shipment->getOrder()->setIsInProcess(true);

try {
// Save created shipment and order
$shipment->save();
$shipment->getOrder()->save();

// Send email notification
$this->_objectManager->create(‘Magento\Shipping\Model\ShipmentNotifier’)
->notify($shipment);

$shipment->save();
} catch (\Exception $e) {
throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
}
}
}
[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.