TransWikia.com

Magento 2 - Add multiple simple product in cart programmatically

Magento Asked on December 28, 2021

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 CatalogProductControllerIndex;
use MagentoFrameworkAppActionAction;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkDataFormFormKey;
use MagentoCheckoutModelCart;
use MagentoCatalogModelProduct;
class Index extends Action
{
    protected $resultPageFactory;
    protected $formKey;   
    protected $cart;
    protected $product;
    public function __construct(
        MagentoFrameworkViewResultPageFactory $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

2 Answers

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 CatalogProductControllerIndex;

use MagentoFrameworkControllerResultFactory;
use MagentoFrameworkAppActionAction;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkDataFormFormKey;
use MagentoFrameworkControllerResultJsonFactory;
use MagentoCheckoutModelCart;
use MagentoCatalogModelProduct;

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

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

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

    /**
     * Constructor.
     *
     * @param Context $context
     * @param MagentoCheckoutModelSession $checkoutSession
     * @param MagentoCustomerModelSession $customerSession
     * @param FormKey $formKey
     * @param Cart $cart
     * @param Product $product
     */
    public function __construct(
        Context $context,
        MagentoFrameworkViewResultPageFactory $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');
            }
        
    }
}

Answered by Jackom on December 28, 2021

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

Answered by Pushpendra Singh on December 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP