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
    Commented Jun 17, 2019 at 14:04
  • Have you get any solution? Commented Feb 12, 2020 at 9:36

1 Answer 1

3

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.

2
  • It works on Magento v2.4.2. Thanks! Commented May 13, 2021 at 8:53
  • How to add bundle product to the cart by using this code? Commented Aug 30, 2021 at 5:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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