We have a requirement that we wants to add product to cart programmatically in magento2.
1 Answer
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();
}
-
-
no need @srg please place the 'code' in your custom controller and submit the form Aug 24, 2017 at 4:57
-
1
-
ok let me check and update you, before that please try with the above code and comment me with u required details Aug 24, 2017 at 5:02
-
2the above code is adding product to guest cart succesfully. can you help me to add product to a registered customer cart using customer id or something like that?– srgAug 24, 2017 at 5:23