How to Create Shipment programmatically in Magento 2?

Learning how to create a shipment programmatically in the Magento platform is a few steps.

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

Need expert support for your Magento marketplace with trendy free live demo? Click here and get started!!!

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

Create Shipment Programmatically in Magento 2

The following are the steps 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 a Shipment Programmatically in Magento 2.

Click here to develop a Magento store in a few days with Webnexs eCommerce solution.

Create Shipment Programmatically in Magento 2


Posted

in

,

by

Comments

Leave a Reply

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