We have a requirement that we wants to add product to cart programmatically in magento2.
Asked
Active
Viewed 2.1k times
1 Answers
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
\Magento\Checkout\Model\Cartis marked as deprecated. Is there een alternative? – Michiel May 02 '18 at 06:13\Magento\Quote\Model\Quote instead– Lukas Komarek Dec 13 '18 at 09:44