I am quite new to Magento and have the requirement to add a predetermined free product to the shopping cart each time the customer adds something else. So far I have added an observer to watch for the 'checkout_cart_product_add_after' event.
I have used the following code in my observer but when I add a product to the cart, a message is displayed saying
"We can't add this product to the basket right now"
use Magento\Framework\Event\ObserverInterface; use Magento\Framework\App\RequestInterface; use Magento\Framework\View\Result\PageFactory; class AddProduct implements ObserverInterface { protected $resultPageFactory; protected $_productRepository; protected $_cart; protected $formKey; public function __construct( \Magento\Catalog\Model\ProductRepository $productRepository, \Magento\Checkout\Model\Cart $cart, \Magento\Framework\Data\Form\FormKey $formKey, PageFactory $resultPageFactory ) { $this->resultPageFactory = $resultPageFactory; $this->_productRepository = $productRepository; $this->_cart = $cart; $this->formKey = $formKey; } public function execute(\Magento\Framework\Event\Observer $observer) { $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(); } }
I hope somebody is able to explain what is going wrong here or point me in a different direction if this approach will not work. I am using version 2.2 of Magento.
Many thanks