TransWikia.com

Add same product to quote as a separate item in Magento 2

Magento Asked by chirag dodia on December 1, 2020

I want to add the same product to quote but separately. Here is my code

 $quote = $this->quote->create();
 $quote->setStore($store);
 $quote->setCurrency();


$skuArray = array('EC1','EC1);

foreach($skuArray as $sku){

$item = null;
$item = $this->productRepository->get($sku);
$addedItem = $quote->addProduct($item, 1);

if ($customer->getId()) {
        $quote->assignCustomer($customer);
    }

$quote->collectTotals();
$quote->save();    
  }

Every time Magento is adding one item in the quote_item table with two qty in quote table. But I want two items added separately in the quote_item table.

I know if we can add a custom option to each item Magento will treat it as a separate item so i have created observer to add a custom option to cart in ‘sales_quote_product_add_after’ event

class AddAfterProduct implements ObserverInterface
{
public function execute(Observer $observer)
{
    $items = $observer->getItems();

    foreach ($items as $item) {

        $additionalOptions = array(
             array(
               'code' => 'custom_option',
               'label' => 'Custom Option',
               'value' => rand(0,1111)
           )
        );
        $item->addOption(
            array(
                'code' => 'additional_options',
                'value' =>  serialize($additionalOptions),
            )
        );
    }
}
}

This is also not working. Can somebody help me with this problem?

One Answer

You do not need to add a custom option to the product. All you need is to create the item object BEFORE adding it to the quote, instead of directly adding the product to the quote and letting Magento create the item.

/** @var MagentoQuoteModelQuoteItem $quoteItem */
$quoteItem = $this->itemFactory->create();
$quoteItem->setPrice(123.33);
$quoteItem->setRowTotal($quoteProduct->getPrice());
$quoteItem->setProductType($quoteProduct->getTypeId());
$quoteItem->setOriginalPrice(123.33);
$quoteItem->setCustomPrice(123.33);
$quoteItem->setOriginalCustomPrice(123.33);
$quoteItem->setQtyOrdered(1);
$quoteItem->setQty(1);
$quoteItem->setProduct($quoteProduct);
$quote->addItem($quoteItem);

I could not find the answer anywhere on the internet. Everything else that I tried failed.

Answered by Andresa Martins on December 1, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP