How to Create Shipment Programmatically in Magento 2

Here are some steps which help to Create Shipment Programmatically in Magento 2.

If we want to create shipment for an order then you can form by following method.For automation magento we need auto create a shipment, so i choose to write this post for create shipment by code.

The following are the steps which used to create a shipment after placing an order it will auto generate shipment:

// 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())

                );

}

I hope the following steps help you to Create Shipment Programmatically in Magento 2

Last Update: April 9, 2018  

February 8, 2018   232   Nandini R    Shipping    
Total 0 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

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

Facebook
Google+
http://www.webnexs.com/blog/kb/create-shipping-programmatically-magento-2
Twitter
LinkedIn