Question

On checkout page, if free shipping available - this option should be already selected. How can I do this in Magento2?

Was it helpful?

Solution

To auto select free shipping on checkout page, you can override a javascript from Magento_Checkout module. for this you have to create your module,

Namespace/Module/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Namespace_Module',
    __DIR__
);

Namespace/Module/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Namespace_Module" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Checkout"/>
        </sequence>
    </module>
</config>

then create the requirejs to overriding the checkout-data-resolver js,

for this

Namespace/Module/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            'Magento_Checkout/js/model/checkout-data-resolver': 'Namespace_Module/js/model/checkout-data-resolver'
        }
    }
};

Now copy checkout-data-resolver.js from Magento_Checkout/view/frontend/web/js/model in our module with the same path Namespace_Module/view/frontend/web/js/model

After that, change a condition inside the function resolveShippingRates

From:

............................

     if (ratesData.length == 1) {
                    //set shipping rate if we have only one available shipping rate
                    selectShippingMethodAction(ratesData[0]);

                    return;
                }

.............................

To

.................................




     var selectedShippingRate = checkoutData . getSelectedShippingRate();
        var availableRate = false;
        if (selectedShippingRate == null) { // custom code start here
            for (var i = 0;i < ratesData . length;i++){
                if (ratesData[i] . method_code == 'freeshipping') {
                    selectShippingMethodAction(ratesData[i]);
                    return;
                }
            }
            } else { // custom code end here
            if (ratesData . length == 1) {
                //set shipping rate if we have only one available shipping rate
                selectShippingMethodAction(ratesData[0]);
                return;
            }
        }

.....................................

Replace Namespace/Module/ with your YOUR_NAMESPACE and YOUR_MODULENAME

  1. Activate the module : php bin/magento module:enable Namespace_Module
  2. Run a setup upgrade : php bin/magento setup:upgrade
  3. Do a static deploy : php bin/magento setup:static-content:deploy

Thanks to @Catalin Ionita

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top