Skip to content

How to Modify Discount amount of cart price rule on cart page in magento 2

I would like to modify Discount Amount of cart price rule on the cart page. Actually Magento apply rule using class MagentoSalesRuleModelRulesApplier and function is protected function setDiscountData($discountData, $item)

So for that, I create a preference to modify Discount Amount

<preference for="MagentoSalesRuleModelRulesApplier" type="NamespaceModulenameModelRulesApplier" />

And my logic like below :

<?php
namespace NamespaceModulenameModel;

use NamespaceModulenameModelSourceShowCoupon;
use MagentoSalesRuleModelQuoteChildrenValidationLocator;
use MagentoSalesRuleModelRuleActionDiscountCalculatorFactory;
use NamespaceModulenameModelSourcePromotionType;

class RulesApplier extends MagentoSalesRuleModelRulesApplier
{
    /**
     * @var MagentoSalesRuleModelResourceModelRuleCollection
     */
    protected $rules;

    /**
     * @var MagentoSalesRuleModelUtility
     */
    protected $validatorUtility;

    public function __construct(
        CalculatorFactory $calculatorFactory,
        MagentoFrameworkEventManagerInterface $eventManager,
        MagentoSalesRuleModelUtility $utility,
        MagentoSalesRuleModelResourceModelRuleCollectionFactory $rulesFactory,
        ChildrenValidationLocator $childrenValidationLocator = null
    ){
        $this->ruleCollection = $rulesFactory;
        parent::__construct($calculatorFactory, $eventManager, $utility, $childrenValidationLocator);
    }

    protected function setDiscountData($discountData, $item)
    {
        $item->setDiscountAmount(0);
        $item->setBaseDiscountAmount(0);
        $item->setOriginalDiscountAmount(0);
        $item->setBaseOriginalDiscountAmount(0);

        $quote = $item->getQuote();
        $quote->setCustomAmount($discountData->getAmount());
        $quote->setBaseCustomAmount($discountData->getBaseAmount());
        //echo '<pre>';print_r($quote->debug());die;
        return $this;
    }
}

In the above code, I am trying to set discount amount to zero and I want to set that discount amount to my custom fee value. but unfortunately, it is not working.

So I debug that and found that if you set $item->setDiscountAmount(0); to zero then the value is not set to your custom fee. so can someone help me to solve out this issue? what’s I am doing wrong or is there any other method available?

In short, I would like to set discount amount to may custom fee and default discount amount($item->setDiscountAmount(0)) to zero at the same time same file

Any help would be appreciated! Thanks.