2

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.

Jafar Pinjar
  • 1,929
  • 7
  • 64
  • 139

3 Answers3

3

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

Saneer Ladani
  • 445
  • 3
  • 10
  • for me quote id not retrieved when inserted first time. – Jafar Pinjar May 10 '19 at 12:12
  • hello @Saneer, I am facing problem, when setting custom price for each product – Jafar Pinjar May 10 '19 at 14:07
  • hi @Saneer, i need to store quoteid in my custom table with product id, but i am getting quoteid as empty here,https://magento.stackexchange.com/questions/274172/quote-id-is-empty-when-inserting-multiple-records-into-cart-in-magento2 – Jafar Pinjar May 13 '19 at 06:31
2

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()
{
    $selectedItems = $this->getRequest()->getPost('selectedItems');      
    //$cart_product = your product data collection or 
    $cart_product = $this->_productFactory->create()->getCollection()->addAttributeToFilter('entity_id',array($selectedItems));

    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
0

I just add 20 sentes. When you use \Magento\Checkout\Model\Cart and method public function addProduct($productInfo, $requestInfo = null)

And your wishes are adding some simples products as coupled on one configurable then don't forget to use only product object for $productInfo with clone: $this->_cart->addProduct(clone $product, $params);

ilia plat
  • 1
  • 1