Reading list Switch to dark mode

    How to create custom cart rule in magento 2

    Updated 29 March 2023

    As you know magento provides us with four types of cart rules.

    But sometimes we need or need to enhance the functionality of the magento cart rule according to the requirement you can have two options either you override the core magento cart rule or create a new cart rule.

    Here we create a new custom cart rule

    for creating a custom cart rule you need to create the below files

    Below the file create just add the option in the dropdown in the rule
    Webkul\CartRule\etc\adminhtml\di.xml

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <type name="Magento\SalesRule\Model\Rule\Metadata\ValueProvider">
            <plugin name="salesrule-plugin" type="Webkul\CartRule\Plugin\Rule\Metadata\ValueProvider" sortOrder="1" />
        </type>
    </config>
    <?php
    
    namespace Webkul\CartRule\Plugin\Rule\Metadata;
    
    class ValueProvider {
        public function afterGetMetadataValues(
            \Magento\SalesRule\Model\Rule\Metadata\ValueProvider $subject,
            $result
        ) {
    
    
            $applyOptions = [
                'label' => __('Custom'),
                'value' => [
                    [
                        'label' => 'Buy X Get next Y with M% discount',
                        'value' => 'buy_x_get_next_y_with_percent',
                    ]
                ],
            ];
            array_push($result['actions']['children']['simple_action']['arguments']['data']['config']['options'], $applyOptions);
            return $result;
        }
    }

    You will see the cart rule in the dropdown

    Now pass the class as an argument in class Magento\SalesRule\Model\Rule\Action\Discount\Calculator
    in below location
    Webkul\CartRule\etc\di.xml

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <type name="Magento\SalesRule\Model\Rule\Action\Discount\CalculatorFactory">
            <arguments>
                <argument name="discountRules" xsi:type="array">
                    <item name="buy_x_get_next_y_with_percent" xsi:type="string">\Webkul\CartRule\Model\Rule\Action\Discount\BuyXGetNextYWithPercent</item>
                </argument>
            </arguments>
         </type>
    </config>
    <?php
    namespace Webkul\Magento\Model\Rule\Action\Discount;
    
    use Magento\SalesRule\Model\Rule\Action\Discount\AbstractDiscount;
    
    class BuyXGetNextYWithPercent extends AbstractDiscount
    {
        /**
         * Calculate Buy X Get next Y with M% discount amount
         *
         * @param \Magento\SalesRule\Model\Rule $rule
         * @param \Magento\Quote\Model\Quote\Item\AbstractItem $item
         * @param float $qty
         * @return \Magento\SalesRule\Model\Rule\Action\Discount\Data
         */
        public function calculate($rule, $item, $qty)
        {
            $rulePercent = min(100, $rule->getDiscountAmount());
            $discountData = $this->_calculate($rule, $item, $qty, $rulePercent);
            
            return $discountData;
        }
    
        /**
         * @param \Magento\SalesRule\Model\Rule $rule
         * @param \Magento\Quote\Model\Quote\Item\AbstractItem $item
         * @param float $qty
         * @param float $rulePercent
         * @return Data
         */
        protected function _calculate($rule, $item, $qty, $rulePercent)
        {
            /** @var \Magento\SalesRule\Model\Rule\Action\Discount\Data $discountData */
            $discountData = $this->discountFactory->create();
    
            /**
             * Calculate your logic here
             */
             
            /** Set the discount price in Price **/
            
            $itemPrice = $this->validator->getItemPrice($item);
            $baseItemPrice = $this->validator->getItemBasePrice($item);
            $itemOriginalPrice = $this->validator->getItemOriginalPrice($item);
            $baseItemOriginalPrice = $this->validator->getItemBaseOriginalPrice($item);
    
            $discountData->setAmount($itemPrice - $discountAmount);
            $discountData->setBaseAmount($baseItemPrice - $discountAmount);
            $discountData->setOriginalAmount($itemOriginalPrice - $discountAmount);
                    $discountData->setBaseOriginalAmount($baseItemOriginalPrice - $discountAmount);
    
    
            return $discountData;
        }
    
    }

    Now Create the rule

    cartRule2

    Webkul also provides a special Magento 2 promotion extension with 14 new Cart Rules –

    You may also check our top-quality Magento 2 Modules and Hire Magento Developers


    Happy Coding 🙂
    Thanks!!

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    2 comments

  • hari prasath
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home