4

Does anybody have clue how to force Magento 2 to not merge into one CartItem the same product on adding to cart?

Let's say I would like to sell ropes and my clients might want to order exactly the same rope but with few different lengths (length is defined by quantity). I would like Magento to add certain products (for example by attribute) always as new CartItem without checking if the same product is actually in cart.

Does anybody struggle with that problem?

1 Answer 1

7

To answer you question:

The matching is done by the method Magento\Quote\Model\Quote\Item::representProduct().
This method checks if a certain item in the cart is the same as the product you are just adding to the cart.
Making this method always return false should make any add to cart action add the product as a new line in the cart.

For this you can use an aroundPlugin.

Create a new module and in the etc/di.xml add this

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Quote\Model\Quote\Item">
        <plugin name="[module]-quote-item" type="[Namespace]\[Module]\Plugin\Quote\Item" />
    </type>
</config>

Then create the file [Namespace]/[Module]/Plugin/Quote/Item.php with this content.

<?php
namespace[Namespace]\[Module]\Plugin\Quote;
use Magento\Quote\Model\Quote\Item as QuoteItem;
class Item
{
    public function aroundRepresentProduct(QuoteItem $subject, \Closure $proceed, $product)
    {
        return false;
    }
}

Or a second option could be this. The code is for Magento 1, but you can adapt it for M2. The event recommended in there, sales_quote_add_item, still exists in M2.

To solve your problem, maybe...
If you are planning to sell ropes with fixed lengths maybe you should use configurable products.

3
  • Thanks for you answer, that's the solution I tried. After debugging I found out that there is also method Magento\Quote\Model\Quote\Item::compare() which is triggered, in some cases, when you are updating product. That function should be overwritten as well and return false. Commented Jan 13, 2017 at 11:23
  • Just want to let you know that even though we have 2 lines in quote item table for a same sku, there is only one line in the quote_item_option table, the second line regarding the second same SKU is skipped. Any thoughts ?
    – Sony
    Commented Oct 15, 2020 at 10:33
  • If i edit cart item and update quantity than cart again merges different line items into one line item Commented Jul 2 at 6:45

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.