0

I am trying to add items to my cart in a custom module and have it half working.

The problem is that it adds the same item in place of every other item.

PHP:

  $products = json_decode($_POST['products'], true) ?? array();

  foreach($products as $purchase){
    $productId = $purchase['productid'];
    $qty = $purchase['quantity'];
    $params = "";
    $params = array(
                  'form_key' => $this->formKey->getFormKey(),
                  'product' => $productId,
                  'qty'   => $qty
              );
      //Load the product based on productID
      $_product = $this->product->load($productId);
      $this->cart->addProduct($_product, $params);
      $this->cart->save();
  }

The products variable contains data similar to this:

[{"productid":"2181","quantity":"1"},{"productid":"2185","quantity":"1"},{"productid":"2189","quantity":"1"},{"productid":"2192","quantity":"1"}]

If this data was used in the php code, it would add the item with productid 4 times, instead of each item once. I am guessing it is something to do with either the $params array or the $_product variable not being reset at the start of the foreach.

How do i make each of the items add correctly with the quantity specified, and also, do i want to be calling this line $this->cart->save(); inside or outside of the foreach?

0

I found That the problem was within the line

$_product = $this->product->load($productId);

Magento does not like this being used in a loop for some reason and so the first product was being added in place of every other product in the array.

I fixed the issue by instead using this line:

$_product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);

This successfully loads the new product each time the foreach loops around.

| improve this answer | |

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.