I'm trying to add number of products to cart at a time using custom module
here is my module code
app/code/Multiple/Addtocart/Controller/Index/Cartadd.php
<?php
namespace Multiple\Addtocart\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Checkout\Model\Cart as CustomerCart;
class Cartadd extends \Magento\Framework\App\Action\Action
{
protected $resultPageFactory;
protected $checkoutSession;
protected $formKey;
protected $request;
protected $cart;
public function __construct(
Context $context,
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Checkout\Model\Session $checkoutSession,
CustomerCart $cart,
PageFactory $resultPageFactory,
array $data = [])
{
$this->formKey = $formKey;
$this->resultPageFactory = $resultPageFactory;
$this->checkoutSession = $checkoutSession;
$this->cart = $cart;
parent::__construct($context);
}
public function execute()
{
$pid=array();
$pid=$_POST['data'];
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
for($i=0;$i<count($pid);$i++){
$product_id=$pid[$i]['id'];
$product_qty=$pid[$i]['qty'];
$_product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);
echo $_product->getName()."<br>";
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' =>$product_id, //product Id
'qty' =>$product_qty //quantity of product
);
//$_product = $this->product->load($tradeProductId);
//$this->cart->truncate();
$this->cart->addProduct($_product, $params);
$this->cart->save();
$this->messageManager->addSuccess(__('Item has been successfully added to cart.'));
}
}
}
app/code/Multiple/Addtocart/etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="add_prodct_addtocart_after">
<observer name="Multiple_Addtocart" instance="Multiple\Addtocart\Observer\CustomPrice" />
</event>
</config>
app/code/Multiple/Addtocart/Observer/CustomPrice.php
<?php
namespace Multiple\Addtocart\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Psr\Log\LoggerInterface;
class CustomPrice implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
$writer = new \Zend\Log\Writer\Stream(BP.'/var/log/multiproduct.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
}
}