PHP SOLUTIONS

This is the blog for getting Idea regarding PHP, Magento, jQuery and JavaScript for Customization.

Thursday 9 November 2017

Magento 2 : Apply Custom Discount to cart

Hi All,

     Offering some special discount to customers is a good way to attract more customers & indirectly increase sales of site !

    In Magento 2,  there are so many ways available for apply some special discounts after adding product to cart, but here some special things which allowed you for add dynamic discount product wise !

  For that need to follow some steps for make it work,

  A) Create "spe_dis" field  with "Decimal" data type in "quote_item" tabel.

  B) Override Add.php from core directory form vendor\magento\module-checkout\Controller\Cart\Add.php

                                                                         OR

  B) For Testing update same file in vendor\magento\module-checkout\Controller\Cart\Add.php

      After, this line $this->cart->save();

      Add below code,

     $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
     $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
     $connection = $resource->getConnection();

     $data=$connection->fetchAll('SELECT item_id FROM quote_item WHERE quote_id='.$this->cart->getQuote()->getId());
     if(isset($_REQUEST['spe_dis']) and $_REQUEST['spe_dis'] > 1){
            $fianlsf = 0;
            foreach($data as $dats){$fianlsf = $dats['item_id'];}
            $sql = "Update quote_item  Set spe_dis='".$_REQUEST['spe_dis']."' where item_id = ".$fianlsf."";
            $connection->query($sql);
      }


     Note :- Above code save special discount value to DB.

   C) Create a hidden text field inside product page form

      <input type="hidden" id="spe_dis" value="0" />

      set special discount to this field which want to apply product wise.

  D) Finally, Unzip files in app/code 

       Note :- Download Zip

     Result would be like ->

This is working for me in Magento 2.1.8 and 2.2.0 also !