0

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);
}
}
  • hi @amith instead of Class Display keep Class Cartadd – NIPPU Sep 21 '17 at 12:23
  • @Nagaraju Kasa i have changed but still 404 page showing – amith lal Sep 21 '17 at 12:29
  • hi @amith just follow the steps below and get back with u r comments thanks – NIPPU Sep 21 '17 at 12:37
1

Step 1:- Template File path:- /app/code/Multiple/Addtocart/view/frontend/templates/addtocart_index_index.phtml

<form name="paytrade-orders-list" id="paytrade-orders-list" action="<?php echo $this->getUrl('addtocart/index/cartadd');?>" method="post" >

<div class="saveandmore">
<button type="submit" class="buyersave"><?php echo _('Pay Now');?></button>
<label><span><?php echo _('Select all');?> </span><input type="checkbox" id="select_all" /></label>
</div>

</form>

Step2:-

/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;
class Cartadd extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory;
    protected $formKey;
    protected $request;

  public function __construct(
    Context $context,
    \Magento\Framework\Data\Form\FormKey $formKey,
    PageFactory $resultPageFactory,
    array $data = []) 
    { 
        $this->formKey = $formKey;
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }


  public function execute()
  {
    echo 'Hello World';   

  }
}

Step 3:- Use di compile and clear cache and full page cache when ever u change the __construct()

as well as use magento2 log whether u r controller is calling or not

  • But here /app/code/Multiple/Addtocart/view/frontend/templates/addtocart_index_index.phtml i dont need this i have alredy added this select box in my list.phtml file and from there i have added a button while clicking that button all selected products id will get in this file Cartdadd.php using ajax – amith lal Sep 21 '17 at 12:43
  • ok in your ajax url use <?php echo $this->getUrl('addtocart/index/cartadd');?> (or) <?php echo $block->getUrl('addtocart/index/cartadd');?> – NIPPU Sep 21 '17 at 12:47
  • 1
    now i can access the module can we go to next step? – amith lal Sep 22 '17 at 5:52
  • 1
    finally its getting worked now the products add in cart but here i have small issue in cart the price of first product is only showing other product price is 0 – amith lal Sep 23 '17 at 6:49
  • 1
    i have fixed every issue except mini cart now i got every thing worked but the issue is in mini cart the item show their but the price and quantity not updating (the issue only in mini cart) – amith lal Sep 25 '17 at 5:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.