I'm trying to add to the cart the simple products of the programmatically configurable product.
For now I have this script that only puts 1 item in the cart and does not update the minicart:
<?php
namespace Catalog\Product\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;
class Index extends Action
{
protected $resultPageFactory;
protected $formKey;
protected $cart;
protected $product;
public function __construct(
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
Context $context,
FormKey $formKey,
Cart $cart,
Product $product) {
$this->formKey = $formKey;
$this->cart = $cart;
$this->product = $product;
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context);
}
public function execute()
{
//INSERIMENTO NEL CARRELLO PER PROD CONFIGURABILE
if($_POST['productType'] == 'configurable'){
$resultRedirect = $this->resultRedirectFactory->create();
$prodIdColl = $this->product->load($_POST['productID']);
$simple_collection = array('valore1','valore2','valore3');
$count = 1;
foreach($simple_collection as $simple_product){
${'prodAddId'.$count} = $_POST['prodCol'.$count.''];
if( $_POST['qtyCol'.$count.''] > 0 ){
${'params'.$count} = array(
'form_key' => $this->formKey->getFormKey(),
'product' => ${'prodAddId'.$count} ,
'qty' => $_POST['qtyCol'.$count.'']
);
${'productCart'.$count} = $this->product->load( ${'prodAddId'.$count} );
$this->_cart->addProduct( ${'productCart'.$count} , ${'params'.$count} );
}
$count++;
}
$this->_cart->save();
return $resultRedirect->setPath('checkout');
}
//INSERIMENTO NEL CARRELLO PER PROD SEMPLICE
if($_POST['productType'] == 'simple'){
$resultRedirect = $this->resultRedirectFactory->create();
$productId = $_POST['productID'];
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' => $productId,
'qty' => $_POST['qtySimple']
);
$product = $this->product->load($productId);
$this->_cart->addProduct($product, $params);
$this->_cart->save();
return $resultRedirect->setPath('checkout');
}
}
}
?>
How can I put all the various simple products in the cart?
Issue with my script: The problem is that this script only adds one product to the cart and not all the other simple products. The quantities instead the sums. For example, if I want to add 3 simple products to the cart, I only add the first one and add the quantities of all 3
Thank you