Add Product to cart by observing an event checkout_cart_product_add_after

<your_magento_directory>/app/code/JD/Floatcart/Observer/AddproductToCart.php :

namespace JD\Floatcart\Observer;


class AddproductToCart implements \Magento\Framework\Event\ObserverInterface{

   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)
   {
       $this->_productRepository = $productRepository;
       $this->_cart = $cart;
       $this->formKey = $formKey;
   }
   public function execute(\Magento\Framework\Event\Observer $observer)
   {
       $item = $observer->getEvent()->getData('quote_item');
       $product = $observer->getEvent()->getData('product');
       $item = ($item->getParentItem() ? $item->getParentItem() : $item);

       //id product that you want add to cart
       $product_id=1023;

       if($product->getId() != $product_id){
           $params = array(
               'product' => $product_id,
               'qty' => $product->getQty()
           );
           $_product = $this->_productRepository->getById($product_id);
           $this->_cart->addProduct($_product,$params);
           $this->_cart->save();
       }

   }

}

To <your_magento_directory>/app/code/JD/Floatcart/etc/events.xml you need add code as this:

<event name="checkout_cart_product_add_after">
   <observer name="addproduct_tocart" instance="JD\Floatcart\Observer\AddproductToCart"/>
</event>

 

4.46 / 5.0
Article rating (13 Reviews)
Do you find this article useful? Please, let us know your opinion and rate the post!
Not badGoodVery GoodGreatAwesome