4

We have a requirement that we wants to add product to cart programmatically in magento2.

Priyank
  • 7,682
  • 7
  • 37
  • 70
srg
  • 455
  • 3
  • 10
  • 27

1 Answers1

14
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()
 { 
  $productId =10;
  $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' => $productId, //product Id
                'qty'   =>1 //quantity of product                
            );              
    //Load the product based on productID   
    $_product = $this->product->load($productId);       
    $this->cart->addProduct($_product, $params);
    $this->cart->save();
 }
Naresh Kumar
  • 130
  • 6
Nagaraju Kasa
  • 5,856
  • 6
  • 53
  • 113