0

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

3 Answers 3

3

I FOUND THE SOLUTION!

This is the complete code for add to cart multiple items programmatically that i write. I hope this help someone ;)

<?php
namespace Catalog\Product\Controller\Index;

use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;

class AddCart extends Action
{
    protected $resultPageFactory;
    /**
     * @var FormKey
     */
    protected $formKey;

    /**
     * @var Cart
     */
    protected $cart;

    /**
     * @var Product
     */
    protected $product;

    /**
     * Constructor.
     *
     * @param Context $context
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param \Magento\Customer\Model\Session $customerSession
     * @param FormKey $formKey
     * @param Cart $cart
     * @param Product $product
     */
    public function __construct(
        Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        FormKey $formKey,
        Cart $cart,
        Product $product
    ) {
        $this->formKey = $formKey;
        $this->cart = $cart;
        $this->product = $product;
        $this->resultPageFactory = $resultPageFactory;
        $this->_resultFactory = $context->getResultFactory();
        parent::__construct($context);
    }

    public function execute()
    {
            $_product = $this->product->load($_POST['productID']);
            
            //INSERIMENTO NEL CARRELLO PER PROD CONFIGURABILE
            if($_POST['productType'] == 'configurable'){    
                $resultRedirect = $this->resultRedirectFactory->create();
                $simple_collection = $_product->getTypeInstance()->getUsedProducts($_product);
                $count = 1;
                
                //AGGIUNTA NEL CARRELLO DEI COLORI
                foreach($simple_collection as $simple_product){

                    if($_POST["qtyCol".$count.""] > 0){
                        ${'params'.$count.''} = $_POST["qtyCol".$count.""];
                        ${'product'.$count.''} = $_POST["prodCol".$count.""];
                        $this->cart->addProduct( ${'product'.$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();
                
                //AGGIUNTA NEL CARRELLO PROD SINGOLO
                $params = $_POST['qtySimple'];              
                $product = $_POST['productID'];  
                
                $this->cart->addProduct($product, $params);
                
                
                $this->cart->save();
                return $resultRedirect->setPath('checkout');
            }
        
    }
}
1

For Minicart update, You need to add action URL in sections.xml file like below ex.

Create a sections file app/code/Vendor/Module/etc/frontend/sections.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="cartupdate/items/add">
        <section name="cart"/>
    </action>
</config>

Update your action url with this cartupdate/items/add

5
  • Ok, thanks man! And for add multiple products can you help me?
    – Jackom
    Commented Jul 24, 2020 at 13:02
  • What is the issue that come with your script in multiple products adding in cart? Commented Jul 27, 2020 at 4:38
  • 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...
    – Jackom
    Commented Jul 27, 2020 at 7:03
  • Try this link magento.stackexchange.com/a/258688/13832 Commented Jul 28, 2020 at 4:14
  • Thanks but I tried this code in this link but i have error "cannot use the create function an object"
    – Jackom
    Commented Jul 28, 2020 at 7:18
0

I was looking for issue as describe @Jackom And I found some one. If you want to add 2 simples with one configurable parrent use object with clone on addProduct method

$this->_cart->addProduct(clone $product, $params);

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.