Magento – Magento2 Split Order Based on Vendor

checkoutmagento-2.1orderssales-quote

I am trying to split the order based on vendor during checkout process. If there are two products in cart from different vendor, order needs to be split based on vendor. I have followed the answer mentioned here and here. Here is the code.

use Magento\Quote\Model\Quote as QuoteEntity;
class QuoteManagement extends \Magento\Quote\Model\QuoteManagement
{

    public function submit( QuoteEntity $quote, $orderData = []) {
        $sortedItems = array();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $logger = \Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface');
        $logger->debug('Quote overriden');
        foreach ($quote->getAllItems() as $item) {
            $product_id = $item->getProduct()->getId();  
            $logger->debug($item->getName());
            $product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);
            $vendor=$product->getResource()->getAttribute('vendor')->getFrontend()->getValue($product);
            if (!isset($sortedItems[$vendor])) {
                $sortedItems[$vendor] = $item;
            }
        }

        $logger->debug(json_encode($sortedItems));
        foreach ($sortedItems as $vendor => $items) {
        foreach ($quote->getAllItems() as $item) {
            $quote->getItemsCollection()->removeItemByKey($item->getId());
        }
        foreach ($items as $item) {
            $quote->addItem($item);
        }
        $quote->setTotalsCollectedFlag(false)->collectTotals();

       parent::submit($quote, $orderData);
    }

        return $this;
    }
}

For some reason the $sortedItems returns vendor in key and value is empty and checkout redirects back to cart page.

Any help on splitting the order during the checkout would be appreciated.

Best Answer

First, You should not use the ObjectManager $product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id); directly!

Also, it seems you may be trying the same approach you would in Magento 1 style. Which can work, but with the code base a work in progress daily it's best to take the proper approach to ensure backwards and forward compatibility.

With that said, you probably will find your answer in the Type models

Hope this helps!

Related Topic