7

I have array of checkbox selected products(entity_id) in my controller
how to add those product to cart directly

Tirth Patel
  • 1,039
  • 8
  • 26

1 Answers1

3

Add this below code in your controller :

protected $formKey;
protected $_productFactory;
protected $_cart;
protected $messageManager;
public function __construct(
    Context $context,
    \Magento\Framework\Data\Form\FormKey $formKey,
    \Magento\Framework\Message\ManagerInterface $managerInterface,
    \Magento\Catalog\Model\ProductFactory $productFactory,
    \Magento\Checkout\Model\Cart $cart
) {
    parent::__construct($context);
    $this->formKey = $formKey;
    $this->_productFactory = $productFactory;
    $this->_cart = $cart;
    $this->messageManager = $managerInterface;
}

public function execute()
{
    //$cart_product = your product data collection or 
    //$cart_product = $this->_productFactory->create()->getCollection()->addAttributeToFilter('entity_id',array('product_id1','product_id2'));
    if ($cart_product) {
        foreach ($cart_product as $key => $value) {
            $custom_optinons_value = '';
            if (isset($value['super_attribute']) || !empty($value['super_attribute'])) {
                $custom_optinons_value = $value['super_attribute'];
            }
            $this->addCartProduct($value['id'], $value['qty'], $custom_optinons_value);
        }
        $this->_cart->save();
    }
    $this->messageManager->addSuccess('Shopping cart updated succesfully.');
}

public function addCartProduct($productID, $productQty, $config_options)
{
    $product = $this->_productFactory->create()->load($productID);
    $info = new \Magento\Framework\DataObject(
        [
            'form_key' => $this->formKey->getFormKey(),
            'product_id' => $productID,
            'qty' => $productQty,
            'super_attribute' => $config_options,
        ]
    );
    return $this->_cart->addProduct($product, $info);
}

Create sections.xml at app/code/VendorName/Abc/etc/frontend

<?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="abc/index/addtocart">
        <section name="cart"/>
    </action>
</config>

Controller path : VendorName/Abc/Controller/Index/Addtocart.php

remove var and generated folder.

Rohan Hapani
  • 17,388
  • 9
  • 54
  • 96