0

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-

module-sales-rule/Model/Rule/Action/Discount/BuyXGetY.php

 public function calculate($rule, $item, $qty)
    {
<snip>
    if($rule->getSimpleAction()=='buy_x_get_y' && ($item->getSku())=='24-UG06'){
                $cart->addProduct('24-UG07','1')->save();
<snip>
            }

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

0

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" />
</event>

Observer File

<?php
    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
            $item->setCustomPrice($price);
            $item->setOriginalCustomPrice($price);
            $item->getProduct()->setIsSuperMode(true);
        }

    }

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.