2

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?

2
  • Try to use below event checkout_cart_add_product_complete and add custom options – nishu Jun 17 '19 at 14:04
  • Have you get any solution? – Kirti Nariya Feb 12 '20 at 9:36
2

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 \Magento\Quote\Model\Quote\Item $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.

1
  • It works on Magento v2.4.2. Thanks! – Sergey Uskov May 13 at 8:53

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.