Autoselect free shipping option on checkout
-
10-12-2020 - |
Pergunta
On checkout page, if free shipping available - this option should be already selected. How can I do this in Magento2?
Solução
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
- Activate the module :
php bin/magento module:enable Namespace_Module
- Run a setup upgrade :
php bin/magento setup:upgrade
- Do a static deploy :
php bin/magento setup:static-content:deploy
Thanks to @Catalin Ionita