以编程的方式创建物流

在 Magento 2 中,要添加你所需要的新物流,最方便的方法就是用编程的方式创建,在 Magento 2 的控制台中运行以下代码可以满足你要做的全部事情。

// Load the order increment ID
$order = $this->_objectManager->create('Magento\Sales\Model\Order')->loadByIncrementID($incrementid);

// OR
$order = $this->_objectManager->create('Magento\Sales\Model\Order')
    ->loadByAttribute('increment_id', '000000001');


//load by order 
$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())
                );
}

这就是全部教程,Mageplaza 强烈建议您以编程方式创建物流。

本教程翻译自Mageplaza模块开发系列,其他内容请点击下面链接: