4

Is it (and if so, how is it) possible to create the following promotion in Magento?

If a certain product item is added to the cart, another certain product shall be added to cart automatically and the price of this second product shall be set to 0.

Thanks a lot for helping!

4

You have to create an observer for checkout_cart_product_add_after event.

app/code/Vendor/Module/etc/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_submit_all_after">
    <observer name="CustomObserver" instance="Vendor\Module\Observer\CustomObserver" />
</event>
</config>

app/code/Vendor/Module/Observer/CustomObserver.php

<?php
namespace Vendor\Module\Observer;

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

class AddCharges 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() != ID ){
            $params = array(
                'product' => ID,
                'qty' => $product->getQty(),
                'price' => 0
            );
            $_product = $this->_productRepository->getById( ID );
            $this->_cart->addProduct($_product,$params);
            $this->_cart->save();
        }

    }
}

Note that the ID is the second products id here.

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.