Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the second product dynamically added to the cart loose it's options in Magento2

I am dynamically adding products to the cart in Magento2 with some custom options. Every product has the same base product id with different options. Represent Product has been properly overridden so that all products added to the cart are separate. However with this code, the second product added will lose it's custom options:

$magento_product = $this->productRepository->get('simple-product-1');
$params = array(
    'product' => $magento_product->getId(),
    'qty'     => intval(5),
    'options' => array(
        'cr_price' => 12.0,
        'Product' => "Test P",
        'cr_XML' => '<root></root>'
    ),
);
$this->cart->addProduct($magento_product, $params);
$params = array(
    'product' => $magento_product->getId(),
    'qty'     => intval(10),
    'options' => array(
        'cr_price' => 14.0,
        'Product' => "Test P2",
        'cr_XML' => '<root></root>'
    ),
);
$this->cart->addProduct($magento_product, $params);
$this->cart->save();

Only the first product has an entry in the quote_item_option table.

Any thoughts on why or how to fix would be appreciated.

like image 936
dubloons Avatar asked Jun 11 '18 18:06

dubloons


1 Answers

Force reloading the product between each add fixes this issue.

$this->productRepository->get('simple-product-1', false, null, true);

The last true parameter is forceReload.

like image 129
dubloons Avatar answered Oct 21 '22 05:10

dubloons