Although I am familiar with Magento1, I am relatively new to Magento2. I need add functionality where a customer buy X product and get different Y product as free. I am overriding the Buy X and get Y free action. I am not able to achieve it. I would appreciate if anyone provide inputs on where to started for this issue.

Below is the code which is not working-


 public function calculate($rule, $item, $qty)
    if($rule->getSimpleAction()=='buy_x_get_y' && ($item->getSku())=='24-UG06'){

I am aware that it is not the best practice to edit core files. I am just playing around the code.


I would use an observer or plugin for this purpose. Here is the method to achieve this through an observer.

In your events.xml

<event name="checkout_cart_product_add_after">
        <observer name="freeproduct" instance="CompanyName\ModuleName\Observer\FileName" />

Observer File

    namespace CompanyName\ModuleName\Observer;

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

    class FileName implements ObserverInterface
        public function execute(\Magento\Framework\Event\Observer $observer) {
            $item = $observer->getEvent()->getData('quote_item');         
            $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
            $price = 0; //set your price here


Hope this helps !!

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.