2

Add a free item in the cart. For example when anyone adds X product in the cart then Y automatic added if remove X then Y automatic remove.

for doing this task I made an observer and an events.xml file, I not getting any result

Thanks

here is my code

observer file

<?php
namespace Feedback\Addon\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;

class CustomObserver implements ObserverInterface
{
    protected $_productRepository;
    protected $_cart;

    public function __construct( \Magento\Catalog\Model\ProductRepository $productRepository, \Magento\Checkout\Model\Cart $cart ){
        $this->_productRepository = $productRepository;
        $this->_cart = $cart;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $product = $observer->getEvent()->getData('product');
        if($product->getId() != 10 ){
            $params = array(
                'product' => 10,
                'qty' => $product->getQty(),
                'price' => 0
            );
            $_product = $this->_productRepository->getById( 10 );
            $this->_cart->addProduct($_product,$params);
            $this->_cart->save();
        }

    }
}

events.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_update_items_after">
    <observer name="CustomObserver" instance="Feedback\Addon\Observer\CustomObserver" />
</event>
</config>
4
  • The data array passed to your observer in the checkout_cart_update_items_after event contains the cart object and an info object with data about the actual cart item. Therefore you will not get the product in the way you are trying in your observer
    – HelgeB
    Feb 4, 2019 at 9:33
  • @HelgeB what should I do for achieving my task... Feb 4, 2019 at 9:35
  • @AkashAgrawal Check my Answer and let me know in the case of any issue Feb 4, 2019 at 13:40
  • @AkashAgrawal if you need code to remove 'Y' item from cart then inform me i will provide Feb 4, 2019 at 13:47

2 Answers 2

3

Try to my below update code on your Observer event file. X product id is 164 and Y product id is 10

namespace Feedback\Addon\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;

class CustomObserver implements ObserverInterface
{
    protected $_product;
    protected $_cart;

    protected $formKey;

    public function __construct(
        \Magento\Catalog\Model\ProductFactory $product,
        \Magento\Framework\Data\Form\FormKey $formKey,
        \Magento\Checkout\Model\Cart $cart
    ){
        $this->_product = $product;
        $this->formKey = $formKey;
        $this->_cart = $cart;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {

        /*$product = $observer->getEvent()->getData('product');*/
        $items = $this->_cart->getQuote()->getAllVisibleItems();
        $isFreeItem = 0;
        $isXItem = 0;
        foreach($items as $item) {
            // X is product id
            if($item->getProductId()=="164"){
                $isXItem = 1;
            }
            // Y is free product id
            if($item->getProductId()=="10"){
                $isFreeItem = 1;
            }
        }

        if(!$isFreeItem && $isXItem) {
            $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product_id' => 10, //product Id
                'qty'   =>1 //quantity of product                
            );
            $_product = $this->_product->create()->load(10);       
            $this->_cart->addProduct($_product, $params);
            $this->_cart->save();
        }
        if(!$isXItem) {
            /* Remove logic here */
        }
    }
}

Update your event from 'checkout_cart_update_items_after' to 'checkout_cart_save_after' to event.xml file . check my below code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_save_after">
        <observer name="CustomObserver" instance="Feedback\Addon\Observer\CustomObserver" />
    </event>
</config>

you need to change your event from checkout_cart_update_items_after to checkout_cart_save_after. because your event call only when cart item will update

Remove generated folder and clear magento cache

2
  • 1
    It helped. this code is to just add item with product but it shows and also adds price of free item in total. it should be zero for free item. Jan 10, 2020 at 11:02
  • @DimplePanchal Have you found this solution yet?
    – nikin
    May 20 at 12:32
0

I found the extension which solve your case name Force Sell.

https://ewebler.com/store/force-sell-magento-2.html

This gives the option to link product X with product Y and Y will automatically add to cart when buying X.

more feature like

  • Add free product to cart
  • Add sample product to cart

Check and thanks me later!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.