0

What would be the correct way to within my Magento 2 module create a shipment, add items to it, and save it? I think the general idea would be to inject:

\Magento\Sales\Api\ShipmentRepositoryInterface $shipmentRepository, 

and do something like:

    $this->shipmentRepository->create();
    $this->shipmentItemFactory->addItems(['order_item_id'=>'qty_to_ship']);
    $this->shipmentRepository-save();

This code doesn't work, but shows what I'm trying to do. I have looked at how Magento itself does it in app/code/Magento/Shipping/Controller/Adminhtml/Order/Shipment/Save.php and it is quite different. Perhaps I have to do it like that, but I'd prefer to use the API as that is what we are supposed to do.

Has anybody used the Service Contract API to do this?

0

After more carefully reviewing the APIs, I don't think there is a way to do this with them. So I've gone ahead and used this code to do what I want:

Inject the shipment factory:

\Magento\Sales\Model\Order\ShipmentFactory $shipmentFactory,

and then:

// Format of $itemArray is [$order_item_id (from sales_order_item)=>$itemShippedQty]
$shipment = $this->shipmentFactory->create($order, $itemArray);
$shipment->register();
$shipment->getOrder()->setIsInProcess(true);
$transaction = $this->_objectManager->create(
    'Magento\Framework\DB\Transaction'
    );
    $transaction->addObject(
    $shipment
    )->addObject(
    $shipment->getOrder()
    )->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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