To select shipping address on checkout in Magento 2 you need to do it by calling select-shipping-address
action. It will set shipping address to quote. You can do it by defining following component:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
define([ 'underscore', 'uiComponent', 'Magento_Customer/js/model/address-list', 'Magento_Checkout/js/action/select-shipping-address', 'Magento_Checkout/js/checkout-data', 'Magento_Checkout/js/model/shipping-rate-service' ], function (_, Component, addressList, selectShippingAddressAction, checkoutData) { 'use strict'; return Component.extend({ /** @inheritdoc */ initObservable: function () { var neededAddress = "42"; _.each(addressList(), function(address) { if (address.getKey() === neededAddress) { selectShippingAddressAction(address); checkoutData.setSelectedShippingAddress(address.getKey()); } }, this); return this; } }); }); |
First we need to understand what shipping address we want to select. After that we go through all addresses in addressList
and call selectShippingAddressAction
. This sets our shipping address to the quote. Then we call checkoutData.setSelectedShippingAddress
method. That sets our address to the localStorage checkout-data.
Shipping rates are recalculated automatically. It happens because quote.shippingAddress has a subscription in Magento_Checkout/js/model/shipping-rate-service.js
. But your shipping address should be set to quote first!!!
To trigger shipping rates to update on checkout you can define Magento_Checkout/js/model/shipping-rate-service
dependency to trigger Magento_Checkout/js/model/shipping-rate-processor/new-address.js::getRates
method directly.
You can define shipping-rate-service.js
in dependencies for it to trigger getRates
method. Otherwise getRates
method can be called before our needed shipping address is set to quote. Thus without this dependency our shipping rates won’t be estimated and there will be no AJAX request to estimate-shipping-methods
.