1

I am trying to create shipment programmatically. Following a tutorial, but facing error on save shipment.

Here is the code that I am using:

$orderId = 100002156;
$order = $this->_orderRepository->get($orderId);

if (!$order->canShip()) {
    echo "Can't Ship";
    die;
}

$orderShipment = $this->_convertOrder->toShipment($order);

foreach ($order->getAllItems() AS $orderItem) {

    if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
        continue;
    }

    $qty = $orderItem->getQtyToShip();
    $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qty);

    $orderShipment->addItem($shipmentItem);
}

$orderShipment->register();
$orderShipment->getOrder()->setIsInProcess(true);

$this->save();
$this->getOrder()->save();

Can anyone tell what is the issue?

2
  • what is the context of your code, in what class do you use this code? And what is the error on which save ($this->save() whatever object $this is or $this->getOrder()->save();?
    – HelgeB
    Apr 4, 2019 at 15:48
  • I am using it in controller
    – Asim Ali
    Apr 4, 2019 at 16:06

1 Answer 1

1

Try This :-

$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderInterface = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface');



$incrementId = "000000165"; //Increment Id
$order = $objectManager->create('Magento\Sales\Model\Order')
        ->loadByAttribute('increment_id', $incrementId);

if ($order->canShip()) {

    $convertOrder = $objectManager->create('Magento\Sales\Model\Convert\Order');
    $shipment = $convertOrder->toShipment($order);

    foreach ($order->getAllItems() AS $orderItem) {

        if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
            continue;
        }
        $qtyShipped = $orderItem->getQtyToShip();

        $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);

        $shipment->addItem($shipmentItem);
    }

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

    try {
        // Save created shipment and order
        $shipment->save();
        $shipment->getOrder()->save();
    } catch (\Exception $e) {
       echo "Shipment Not Created". $e->getMessage(); exit;
    }

    echo "Shipment Succesfully Generated for order: #".$incrementId;
} else {
    echo "Shipment Not Created Becuase It's already created or something went wrong";
}
2
  • Thanks Ronak Rathod, will try this
    – Asim Ali
    Apr 4, 2019 at 16:06
  • Working Or Not ??? Most Welcome Apr 4, 2019 at 16:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.