How to add product to cart programmatically in Magento 2.2.0 ?
I have tried below code but when I do not get Quote item id in Validate method of below file.
\Magento\AdvancedSalesRule\Model\Rule\Condition\Product.php
Code:
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 = 32;
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' => $productId,
'qty' => 2
);
$_product = $this->product->load($productId);
$this->cart->addProduct($_product, $params);
$this->cart->save();
}
Sales Rule Validate Method Code:
File: \Magento\AdvancedSalesRule\Model\Rule\Condition\Product.php
Method:
public function validate(\Magento\Framework\Model\AbstractModel $model)
{
//@todo reimplement this method when is fixed MAGETWO-5713
/** @var \Magento\Catalog\Model\Product $product */
$product = $model->getProduct();
if (!$product instanceof \Magento\Catalog\Model\Product) {
$product = $this->productRepository->getById($model->getProductId());
}
if ($model instanceof \Magento\Quote\Model\Quote\Item) {
die($model->getItemId()); //NULL
Thanks