Magento 2 – How to Add Multiple Items to Cart

addtocartajaxcontrollersmagento2

I am implementing add to cart functionality from ajax using product id.

This is my code of template file

  <tr class="border_bottom child-items  selected">
                        <td >11</td>                            
                        <td>Test 2</td>
                    </tr>
  <tr class="border_bottom child-items  selected">
                        <td >12</td>                            
                        <td>Test 2</td>
                    </tr>

 <script>
 var selectedItems = [];
    jQuery("#table tr.selected").each(function(){
        selectedItems.push(jQuery('td:first', this).html());
    });
    var additemUrl = "<?php echo $this->getUrl().'product/addproduct/additems' ?>";
        jQuery.ajax({
             url: additemUrl,
             type: "POST",
             data : 'selectedItems='+selectedItems,
             dataType: 'json',
             success : function(result) {
                console.log('success');                               
             }
        }); 
   </script>

Here is my controller file.

 use Magento\Framework\Controller\ResultFactory;
 use Magento\Framework\App\Action\Action;
 use Magento\Framework\App\Action\Context;

class AddItems extends Action {
protected $formKey;   
protected $cart;
protected $product;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Data\Form\FormKey $formKey,
    \Magento\Checkout\Model\Cart $cart,
    \Magento\Catalog\Model\Product $product,
    array $data = []) {
        $this->formKey = $formKey;
        $this->cart = $cart;
        $this->product = $product;      
        parent::__construct($context);
    }

public function execute()
 { 
   $selectedItems = $this->getRequest()->getPost('selectedItems');      
    echo '<pre>';
    print_r($selectedItems);exit;
  try{
      $params = array(
                    'form_key' => $this->formKey->getFormKey(),
                    'product' => $selectedItems, //product Id
                    'qty'   =>1 //quantity of product                
                );              
        //Load the product based on productID   
        $_product = $this->product->load($selectedItems);       
        $this->cart->addProduct($_product, $params);
        $this->cart->save();
        $status = 1;    
  }
  catch (\Magento\Framework\Exception\LocalizedException $e) {
         $this->messageManager->addException(
             $e,
             __('%1', $e->getMessage())
         );
          $status = 0;
     } catch (\Exception $e) {
         $this->messageManager->addException($e, __('error.'));
          $status = 0;
     }  
    $result = array();
    $result['status'] = $status;
    $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
    $resultJson->setData($result);
    return $resultJson;
   }
 }

Here i need to read each element from the selectedItems array and add to cart. How this can be implemented.

If only item passed from the ajax , I need to add only one item to the cart.

Can anyone help me on this issue please.

Best Answer

Replace your controller with below code

 use Magento\Framework\Controller\ResultFactory;
 use Magento\Framework\App\Action\Action;
 use Magento\Framework\App\Action\Context;

/**
 * Responsible for loading page content.
 *
 * This is a basic controller that only loads the corresponding layout file. It may duplicate other such
 * controllers, and thus it is considered tech debt. This code duplication will be resolved in future releases.
 */
class AddItems extends \Magento\Framework\App\Action\Action
{

    protected $formKey;   
    protected $cart;
    protected $product;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Data\Form\FormKey $formKey,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Catalog\Model\ProductFactory $product,
        array $data = []
    ) {
        $this->formKey = $formKey;
        $this->cart = $cart;
        $this->product = $product;      
        parent::__construct($context);
    }

    public function execute()
    { 
       $selectedItems = $this->getRequest()->getPost('selectedItems');      
        $selectedItems = explode(",",$selectedItems);
        try{
        foreach ($selectedItems as $key => $selectedItem) {

            $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product_id' => $selectedItem, //product Id
                'qty'   =>1 //quantity of product                
            );
            $_product = $this->product->create()->load($selectedItem);       
            $this->cart->addProduct($_product, $params);
        }
            $this->cart->save();
            $status = 1;
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $this->messageManager->addException($e,__('%1', $e->getMessage()));
            $status = 0;
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('error.'));
            $status = 0;
        }
        $result = array();
        $result['status'] = $status;
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($result);
        return $resultJson;
    }
}

Remove generated folder.

Please check it and let me know in the case of any issue

Related Topic