Okay, I have figured out how to set the shipping method programmatically:
Firstly, all my dependencies:
define(
[
'ko',
'jquery',
'Magento_Ui/js/form/form',
'uiRegistry',
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/resource-url-manager',
'Magento_Checkout/js/action/create-shipping-address',
'Magento_Checkout/js/model/error-processor',
'Magento_Checkout/js/model/shipping-service',
'Magento_Checkout/js/model/cart/totals-processor/default',
'Magento_Checkout/js/model/shipping-rate-registry',
'Magento_Checkout/js/action/select-shipping-method',
'Magento_Checkout/js/checkout-data'
],
function (
ko,
$,
Component,
uiRegistry,
quote,
resourceUrlManager,
createShippingAddress,
errorProcessor,
shippingService,
totalsDefaultProvider,
rateRegistry,
selectShippingMethodAction,
checkoutData
) {
...
Then, the magic promise:
setShippingMethod: function (carrier, method, title) {
return new Promise((resolve, reject) => {
let data = {
carrier_code: carrier,
method_code: method,
carrier_title: title,
method_title: title
};
selectShippingMethodAction(data);
checkoutData.setSelectedShippingRate(code + '_' + method);
if (quote.shippingMethod()) {
resolve(quote.shippingMethod());
} else {
reject(quote.shippingMethod());
}
});
}
So then in your event (or whatever):
setShippingMethod(
methodData['carrier_code'], methodData['warehouse_id'], methodData['title']
).then(
(shippingMethod) => {
totalsDefaultProvider.estimateTotals(quote.shippingAddress());
}
).catch(
(err) => failHandlerMethod(err)
);
Optional, you can also add the shipping address:
let payload = JSON.stringify({
addressInformation: {
address: {
countryId: "country",
postcode: "postcode",
regionId: "region"
},
shipping_carrier_code: "carrier_code",
shipping_method_code: "method_code"
}
});
let addr = createShippingAddress(payload);
rateRegistry.set(address.getCacheKey(), addr);
Best Answer
First, you define a new element in
shippingAdditional
by creating fileview/frontend/layout/checkout_index_index.xml
like thisThen create file
view/frontend/web/js/view/checkout/shipping/carrier_custom.js
as thisAnd then create a file
view/frontend/web/template/checkout/shipping/carrier_custom.html
Basically XML file tells checkout to initiate js file which is an uiComponent. It initiates knockout template and uses
selectedMethod
function to get the value of the currently selected shipping (carrier_method). If the value is what you want it will show the block. You can modify it according to your needs, ie. checking only selected carrier. BecauseselectedMethod
is defined asknockout.computed()
it will get re-evaluated every time user changes the carrier becausequote.shippingMethod()
is an observable.i updated because the template path was wrong