I have array of checkbox selected products(entity_id) in my controller
how to add those product to cart directly
1 Answer
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.
-
-
-
here is one issue product added successfully but only first selected product price is display in mini cart and cart page also , and the other all product price shows 0 Sep 26, 2018 at 7:44
-
You need to pass all values which mention in parameter. $cart_product should be array of all products. Sep 26, 2018 at 12:21
-
in my case $cart_product is array of products entity_id after submiting form Sep 28, 2018 at 4:42