Posted on

Magento2: Add image to specific shipping method defined in module settings every time the checkout updates

I am developing a module for Magento2 that adds a image next to a specific shipping method on checkout and I am lost on how to get this done.

The shipping method in question is not custom made only carrier label is modified in shipping settings (in added picture the method is called “Test”). I also have a module configuration page where you enter the names of shipping methods you want this image to display next to.

My goal is to add image next to every shipping method that is defined in custom module settings on every checkout update.

I notice that checkout updates everytime a country, postcode or address is changed with a REST API call to “estimate-shipping-methods”. I am looking for a way to override this method and add image to shipping options defined in module settings every time this call is made.

What I have done so far successfully:

created a module configuration page where I can enter the shipping methods that I want the image displayed next to.
overriden checkout_index_index.xml shippingAddress component so I can add my custom JS file (shiny.js).
created a sampleConfigProvider which gets shipping methods from configuration page to my custom JS file succesfully.

Module settings


VendorName/ModuleName/view/frontend/layout/checkout_index_index.xml

define(
[
“uiComponent”,
‘ko’,
‘jquery’,
‘domReady’,
],
function(
Component,
ko,
$
) {
$(document).ready(function (){
var checkExist = setInterval(function() {
if ($(‘.loading-mask’).length==0) {
AddImage();
clearInterval(checkExist);
}
}, 100); // check every 100ms

‘use strict’;
return Component.extend({
defaults: {
template: ‘VendorName_ModuleName/shiny’
},
initialize: function () {
this._super(); //you must call super on components or they will not render
},
getTest: function () {
return window.checkoutConfig.ps.test; –> returns successfully
}
});

VendorName/ModuleName/view/frontend/web/js/view/shiny.js

What I tried and failed:

in my custom JS file I check for checkout loader to finish loading, then I display the image, but problem with this method is the checkout updates on certain fields change which reload the shipping method form and removes the image.

Leave a Reply

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