What Programmatically Triggers Magento 2's Shipping Rates to UpdateMagento 2 checkout: How to trigger...
One verb to replace 'be a member of' a club
How does a dynamic QR code work?
How do conventional missiles fly?
Knowledge-based authentication using Domain-driven Design in C#
How badly should I try to prevent a user from XSSing themselves?
Why was Sir Cadogan fired?
How to Prove P(a) → ∀x(P(x) ∨ ¬(x = a)) using Natural Deduction
Does Dispel Magic work on Tiny Hut?
What is the opposite of "eschatology"?
files created then deleted at every second in tmp directory
Where would I need my direct neural interface to be implanted?
What is a Samsaran Word™?
Getting extremely large arrows with tikzcd
Implication of namely
In Bayesian inference, why are some terms dropped from the posterior predictive?
Theorists sure want true answers to this!
GFCI outlets - can they be repaired? Are they really needed at the end of a circuit?
Is it possible to create a QR code using text?
Why do I get negative height?
What is the most common color to indicate the input-field is disabled?
How to travel to Japan while expressing milk?
Different meanings of こわい
How seriously should I take size and weight limits of hand luggage?
How can saying a song's name be a copyright violation?
What Programmatically Triggers Magento 2's Shipping Rates to Update
Magento 2 checkout: How to trigger shipping methods block update programmatically?Internal Server Error (500) estimate-shipping-methodsInvalid XML - Element 'config': Missing child element(s)?Magento 2: How shipping rest api function called On Checkout?update and data: elems in shipping-address/list.htmlHow to get estimate shipping method in magento 2?Shipping modules does not update rate on zip code changes in guest-checkout page Magento 2 production modeMagento2 get Shipping Rates ProgrammaticallySorry, no quotes are available for this order at this time | Magento 2How to update shipping methods on change of custom dropdown on cart pageMagento 2.1 - How to set shipping method at Checkout page programmatically
When you're filling out the Shipping Address form in Magento 2, periodically Magento will make an ajax request for the URL
http://magento.example.com/rest/default/V1/guest-carts/[hash]/estimate-shipping-methods
and use this data to update the shipping methods section of the UI.
Programmatically speaking, which RequireJS modules setup the events and/or Knockout observables or data-bindings that enable this functionality. Tracing backwards through the code from the URL manager
#File: vendor/magento/module-checkout/view/frontend/web/js/model/resource-url-manager.js
getUrlForEstimationShippingMethodsForNewAddress: function(quote) {
var params = (this.getCheckoutMethod() == 'guest') ? {quoteId: quote.getQuoteId()} : {};
var urls = {
'guest': '/guest-carts/:quoteId/estimate-shipping-methods',
'customer': '/carts/mine/estimate-shipping-methods'
};
return this.getUrl(urls, params);
},
has branched too many times for this to be an easy thing to figure out. I'm hoping someone here already has the solution in hand.
magento2 javascript uicomponent knockoutjs
add a comment |
When you're filling out the Shipping Address form in Magento 2, periodically Magento will make an ajax request for the URL
http://magento.example.com/rest/default/V1/guest-carts/[hash]/estimate-shipping-methods
and use this data to update the shipping methods section of the UI.
Programmatically speaking, which RequireJS modules setup the events and/or Knockout observables or data-bindings that enable this functionality. Tracing backwards through the code from the URL manager
#File: vendor/magento/module-checkout/view/frontend/web/js/model/resource-url-manager.js
getUrlForEstimationShippingMethodsForNewAddress: function(quote) {
var params = (this.getCheckoutMethod() == 'guest') ? {quoteId: quote.getQuoteId()} : {};
var urls = {
'guest': '/guest-carts/:quoteId/estimate-shipping-methods',
'customer': '/carts/mine/estimate-shipping-methods'
};
return this.getUrl(urls, params);
},
has branched too many times for this to be an easy thing to figure out. I'm hoping someone here already has the solution in hand.
magento2 javascript uicomponent knockoutjs
add a comment |
When you're filling out the Shipping Address form in Magento 2, periodically Magento will make an ajax request for the URL
http://magento.example.com/rest/default/V1/guest-carts/[hash]/estimate-shipping-methods
and use this data to update the shipping methods section of the UI.
Programmatically speaking, which RequireJS modules setup the events and/or Knockout observables or data-bindings that enable this functionality. Tracing backwards through the code from the URL manager
#File: vendor/magento/module-checkout/view/frontend/web/js/model/resource-url-manager.js
getUrlForEstimationShippingMethodsForNewAddress: function(quote) {
var params = (this.getCheckoutMethod() == 'guest') ? {quoteId: quote.getQuoteId()} : {};
var urls = {
'guest': '/guest-carts/:quoteId/estimate-shipping-methods',
'customer': '/carts/mine/estimate-shipping-methods'
};
return this.getUrl(urls, params);
},
has branched too many times for this to be an easy thing to figure out. I'm hoping someone here already has the solution in hand.
magento2 javascript uicomponent knockoutjs
When you're filling out the Shipping Address form in Magento 2, periodically Magento will make an ajax request for the URL
http://magento.example.com/rest/default/V1/guest-carts/[hash]/estimate-shipping-methods
and use this data to update the shipping methods section of the UI.
Programmatically speaking, which RequireJS modules setup the events and/or Knockout observables or data-bindings that enable this functionality. Tracing backwards through the code from the URL manager
#File: vendor/magento/module-checkout/view/frontend/web/js/model/resource-url-manager.js
getUrlForEstimationShippingMethodsForNewAddress: function(quote) {
var params = (this.getCheckoutMethod() == 'guest') ? {quoteId: quote.getQuoteId()} : {};
var urls = {
'guest': '/guest-carts/:quoteId/estimate-shipping-methods',
'customer': '/carts/mine/estimate-shipping-methods'
};
return this.getUrl(urls, params);
},
has branched too many times for this to be an easy thing to figure out. I'm hoping someone here already has the solution in hand.
magento2 javascript uicomponent knockoutjs
magento2 javascript uicomponent knockoutjs
asked Nov 12 '16 at 22:10
Alan StormAlan Storm
29.1k21119309
29.1k21119309
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rate-service.js:21 there is a subscribe to the shipping address observerable quote.shippingAddress.
quote.shippingAddress.subscribe(function () {
var type = quote.shippingAddress().getType();
if (processors[type]) {
processors[type].getRates(quote.shippingAddress());
} else {
processors.default.getRates(quote.shippingAddress());
}
});
In the callback funtion this calls to the getRates function in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rate-processor/new-address.js
getRates does an ajax call using the url build via the getUrlForEstimationShippingMethodsForNewAddress method you mentioned in your question and uses the result to update the rateRegistry and sets the shipping rates on the shippingRates observerable of the shipping service.
getRates: function (address) {
shippingService.isLoading(true);
var cache = rateRegistry.get(address.getCacheKey()),
serviceUrl = resourceUrlManager.getUrlForEstimationShippingMethodsForNewAddress(quote),
payload = JSON.stringify({
address: {
'street': address.street,
'city': address.city,
'region_id': address.regionId,
'region': address.region,
'country_id': address.countryId,
'postcode': address.postcode,
'email': address.email,
'customer_id': address.customerId,
'firstname': address.firstname,
'lastname': address.lastname,
'middlename': address.middlename,
'prefix': address.prefix,
'suffix': address.suffix,
'vat_id': address.vatId,
'company': address.company,
'telephone': address.telephone,
'fax': address.fax,
'custom_attributes': address.customAttributes,
'save_in_address_book': address.saveInAddressBook
}
}
);
if (cache) {
shippingService.setShippingRates(cache);
shippingService.isLoading(false);
} else {
storage.post(
serviceUrl, payload, false
).done(
function (result) {
rateRegistry.set(address.getCacheKey(), result);
shippingService.setShippingRates(result);
}
).fail(
function (response) {
shippingService.setShippingRates([]);
errorProcessor.process(response);
}
).always(
function () {
shippingService.isLoading(false);
}
);
}
}
The above show how the shipping methods get updated below will show how the quote.shippingAddres.subscribe is triggered:
The short version
Each shipping method has validation rules set against some of the shipping fields, these fields plus the postcode fields are observered via the knockoutjs 'value' binding and once this is triggered it updates the shipping address and this in turn as mentioned previously updates the shipping methods.
The long version
I will now explain the long version looking at the free shipping method, as this seems to be the same for all other included shipping methods.
on page load The view component Magento_OfflineShipping/js/view/shipping-rates-validation/freeshipping gets loaded via vendor/magento/module-offline-shipping/view/frontend/layout/checkout_index_index.xml
This makes a call to
defaultShippingRatesValidationRules.registerRules('freeshipping', freeshippingShippingRatesValidationRules);
which uses the following
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*global define*/
define(
[],
function () {
"use strict";
return {
getRules: function() {
return {
'country_id': {
'required': true
}
};
}
};
}
from vendor/magento/module-offline-shipping/view/frontend/web/js/model/shipping-rates-validation-rules/freeshipping.js
to set up the rateRules in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rates-validation-rules.js
after this the vendor/magento/module-checkout/view/frontend/web/js/view/shipping.js module gets loaded, which on initialize calls:
shippingRatesValidator.initFields(fieldsetName);
from vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rates-validator.js
initFields: function (formPath) {
var self = this,
elements = shippingRatesValidationRules.getObservableFields();
if ($.inArray(postcodeElementName, elements) === -1) {
// Add postcode field to observables if not exist for zip code validation support
elements.push(postcodeElementName);
}
$.each(elements, function (index, field) {
uiRegistry.async(formPath + '.' + field)(self.doElementBinding.bind(self));
});
},
where
elements = shippingRatesValidationRules.getObservableFields();
uses the previously set up rate rules to get the fields to observe
it then adds the postcode fields if it is not set up yet and calls doElementBinding method on each element which calls this.bindHandler, which has the following:
element.on('value', function () {
clearTimeout(self.validateAddressTimeout);
self.validateAddressTimeout = setTimeout(function () {
if (self.postcodeValidation()) {
self.validateFields();
}
}, delay);
});
which calls self.validateFields();
validateFields: function () {
var addressFlat = addressConverter.formDataProviderToFlatData(
this.collectObservedData(),
'shippingAddress'
),
address;
if (this.validateAddressData(addressFlat)) {
address = addressConverter.formAddressDataToQuoteAddress(addressFlat);
selectShippingAddress(address);
}
},
which calls selectShippingAddress(address); which in turn sets the shippingAddress observerable.
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*global define*/
define(
[
'Magento_Checkout/js/model/quote'
],
function(quote) {
'use strict';
return function(shippingAddress) {
quote.shippingAddress(shippingAddress);
};
}
);
+1 for useful information, but this doesn't explain what triggers the observable on the shipping address object. Are there blur events on the front end fields that update the quote object -- other observables? Something else?
– Alan Storm
Nov 13 '16 at 22:12
@AlanStorm updated my answer
– Martijn Schot
Nov 15 '16 at 22:22
Thanks @martijn, marking this as best for now. I've been working on my own version and (as you seem to understand) a single Stack Overflow answer isn't going to do it.
– Alan Storm
Nov 16 '16 at 22:11
And my version of same, for anyone that's interested in a different path magento-quickies.alanstorm.com/post/153277368585/…
– Alan Storm
Nov 16 '16 at 23:33
Hi @alan,@Martjin ->example.com/rest/default/V1/carts/mine/… //sometime url not loading proper on cart estimation summary due to js issue so can we load it hardly even there are some JS issues in Console?If not then in which file can we check url return data so can debug properly?
– akgola
Sep 4 '17 at 6:52
|
show 1 more comment
To force reloading of shipping methods try,
define(
[
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/shipping-rate-processor/new-address',
'Magento_Checkout/js/model/shipping-rate-processor/customer-address',
'Magento_Checkout/js/model/shipping-rate-registry'
],
function (quote, defaultProcessor, customerAddressProcessor, rateRegistry) {
'use strict';
var processors = [];
rateRegistry.set(quote.shippingAddress().getCacheKey(), null);
processors.default = defaultProcessor;
processors['customer-address'] = customerAddressProcessor;
var type = quote.shippingAddress().getType();
if (processors[type]) {
processors[type].getRates(quote.shippingAddress());
} else {
processors.default.getRates(quote.shippingAddress());
}
}
);
not post the updated address when I use this one code.
– Magento2 Devloper
Mar 7 '18 at 11:22
I did reload the the shipping-method-item.html for me with this code.
– Juliano Vargas
May 23 '18 at 11:27
add a comment |
You can first call selectShippingAddressAction. That will set your shipping address to quote.shippingAddress. After that you can setSelectedShippingAddress to checkoutData.
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;
}
});
});
Shipping rates are recalculated automatically 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.
If you want 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.
I defined shipping-rate-service.js in dependencies for it to trigger getRates methods because otherwise getRates method is called before our needed shipping address is set to quote. That's why without this dependency our shipping rates won't be estimated and there will be no AJAX request to estimate-shipping-methods
add a comment |
Your Answer
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "479"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f145483%2fwhat-programmatically-triggers-magento-2s-shipping-rates-to-update%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rate-service.js:21 there is a subscribe to the shipping address observerable quote.shippingAddress.
quote.shippingAddress.subscribe(function () {
var type = quote.shippingAddress().getType();
if (processors[type]) {
processors[type].getRates(quote.shippingAddress());
} else {
processors.default.getRates(quote.shippingAddress());
}
});
In the callback funtion this calls to the getRates function in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rate-processor/new-address.js
getRates does an ajax call using the url build via the getUrlForEstimationShippingMethodsForNewAddress method you mentioned in your question and uses the result to update the rateRegistry and sets the shipping rates on the shippingRates observerable of the shipping service.
getRates: function (address) {
shippingService.isLoading(true);
var cache = rateRegistry.get(address.getCacheKey()),
serviceUrl = resourceUrlManager.getUrlForEstimationShippingMethodsForNewAddress(quote),
payload = JSON.stringify({
address: {
'street': address.street,
'city': address.city,
'region_id': address.regionId,
'region': address.region,
'country_id': address.countryId,
'postcode': address.postcode,
'email': address.email,
'customer_id': address.customerId,
'firstname': address.firstname,
'lastname': address.lastname,
'middlename': address.middlename,
'prefix': address.prefix,
'suffix': address.suffix,
'vat_id': address.vatId,
'company': address.company,
'telephone': address.telephone,
'fax': address.fax,
'custom_attributes': address.customAttributes,
'save_in_address_book': address.saveInAddressBook
}
}
);
if (cache) {
shippingService.setShippingRates(cache);
shippingService.isLoading(false);
} else {
storage.post(
serviceUrl, payload, false
).done(
function (result) {
rateRegistry.set(address.getCacheKey(), result);
shippingService.setShippingRates(result);
}
).fail(
function (response) {
shippingService.setShippingRates([]);
errorProcessor.process(response);
}
).always(
function () {
shippingService.isLoading(false);
}
);
}
}
The above show how the shipping methods get updated below will show how the quote.shippingAddres.subscribe is triggered:
The short version
Each shipping method has validation rules set against some of the shipping fields, these fields plus the postcode fields are observered via the knockoutjs 'value' binding and once this is triggered it updates the shipping address and this in turn as mentioned previously updates the shipping methods.
The long version
I will now explain the long version looking at the free shipping method, as this seems to be the same for all other included shipping methods.
on page load The view component Magento_OfflineShipping/js/view/shipping-rates-validation/freeshipping gets loaded via vendor/magento/module-offline-shipping/view/frontend/layout/checkout_index_index.xml
This makes a call to
defaultShippingRatesValidationRules.registerRules('freeshipping', freeshippingShippingRatesValidationRules);
which uses the following
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*global define*/
define(
[],
function () {
"use strict";
return {
getRules: function() {
return {
'country_id': {
'required': true
}
};
}
};
}
from vendor/magento/module-offline-shipping/view/frontend/web/js/model/shipping-rates-validation-rules/freeshipping.js
to set up the rateRules in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rates-validation-rules.js
after this the vendor/magento/module-checkout/view/frontend/web/js/view/shipping.js module gets loaded, which on initialize calls:
shippingRatesValidator.initFields(fieldsetName);
from vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rates-validator.js
initFields: function (formPath) {
var self = this,
elements = shippingRatesValidationRules.getObservableFields();
if ($.inArray(postcodeElementName, elements) === -1) {
// Add postcode field to observables if not exist for zip code validation support
elements.push(postcodeElementName);
}
$.each(elements, function (index, field) {
uiRegistry.async(formPath + '.' + field)(self.doElementBinding.bind(self));
});
},
where
elements = shippingRatesValidationRules.getObservableFields();
uses the previously set up rate rules to get the fields to observe
it then adds the postcode fields if it is not set up yet and calls doElementBinding method on each element which calls this.bindHandler, which has the following:
element.on('value', function () {
clearTimeout(self.validateAddressTimeout);
self.validateAddressTimeout = setTimeout(function () {
if (self.postcodeValidation()) {
self.validateFields();
}
}, delay);
});
which calls self.validateFields();
validateFields: function () {
var addressFlat = addressConverter.formDataProviderToFlatData(
this.collectObservedData(),
'shippingAddress'
),
address;
if (this.validateAddressData(addressFlat)) {
address = addressConverter.formAddressDataToQuoteAddress(addressFlat);
selectShippingAddress(address);
}
},
which calls selectShippingAddress(address); which in turn sets the shippingAddress observerable.
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*global define*/
define(
[
'Magento_Checkout/js/model/quote'
],
function(quote) {
'use strict';
return function(shippingAddress) {
quote.shippingAddress(shippingAddress);
};
}
);
+1 for useful information, but this doesn't explain what triggers the observable on the shipping address object. Are there blur events on the front end fields that update the quote object -- other observables? Something else?
– Alan Storm
Nov 13 '16 at 22:12
@AlanStorm updated my answer
– Martijn Schot
Nov 15 '16 at 22:22
Thanks @martijn, marking this as best for now. I've been working on my own version and (as you seem to understand) a single Stack Overflow answer isn't going to do it.
– Alan Storm
Nov 16 '16 at 22:11
And my version of same, for anyone that's interested in a different path magento-quickies.alanstorm.com/post/153277368585/…
– Alan Storm
Nov 16 '16 at 23:33
Hi @alan,@Martjin ->example.com/rest/default/V1/carts/mine/… //sometime url not loading proper on cart estimation summary due to js issue so can we load it hardly even there are some JS issues in Console?If not then in which file can we check url return data so can debug properly?
– akgola
Sep 4 '17 at 6:52
|
show 1 more comment
in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rate-service.js:21 there is a subscribe to the shipping address observerable quote.shippingAddress.
quote.shippingAddress.subscribe(function () {
var type = quote.shippingAddress().getType();
if (processors[type]) {
processors[type].getRates(quote.shippingAddress());
} else {
processors.default.getRates(quote.shippingAddress());
}
});
In the callback funtion this calls to the getRates function in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rate-processor/new-address.js
getRates does an ajax call using the url build via the getUrlForEstimationShippingMethodsForNewAddress method you mentioned in your question and uses the result to update the rateRegistry and sets the shipping rates on the shippingRates observerable of the shipping service.
getRates: function (address) {
shippingService.isLoading(true);
var cache = rateRegistry.get(address.getCacheKey()),
serviceUrl = resourceUrlManager.getUrlForEstimationShippingMethodsForNewAddress(quote),
payload = JSON.stringify({
address: {
'street': address.street,
'city': address.city,
'region_id': address.regionId,
'region': address.region,
'country_id': address.countryId,
'postcode': address.postcode,
'email': address.email,
'customer_id': address.customerId,
'firstname': address.firstname,
'lastname': address.lastname,
'middlename': address.middlename,
'prefix': address.prefix,
'suffix': address.suffix,
'vat_id': address.vatId,
'company': address.company,
'telephone': address.telephone,
'fax': address.fax,
'custom_attributes': address.customAttributes,
'save_in_address_book': address.saveInAddressBook
}
}
);
if (cache) {
shippingService.setShippingRates(cache);
shippingService.isLoading(false);
} else {
storage.post(
serviceUrl, payload, false
).done(
function (result) {
rateRegistry.set(address.getCacheKey(), result);
shippingService.setShippingRates(result);
}
).fail(
function (response) {
shippingService.setShippingRates([]);
errorProcessor.process(response);
}
).always(
function () {
shippingService.isLoading(false);
}
);
}
}
The above show how the shipping methods get updated below will show how the quote.shippingAddres.subscribe is triggered:
The short version
Each shipping method has validation rules set against some of the shipping fields, these fields plus the postcode fields are observered via the knockoutjs 'value' binding and once this is triggered it updates the shipping address and this in turn as mentioned previously updates the shipping methods.
The long version
I will now explain the long version looking at the free shipping method, as this seems to be the same for all other included shipping methods.
on page load The view component Magento_OfflineShipping/js/view/shipping-rates-validation/freeshipping gets loaded via vendor/magento/module-offline-shipping/view/frontend/layout/checkout_index_index.xml
This makes a call to
defaultShippingRatesValidationRules.registerRules('freeshipping', freeshippingShippingRatesValidationRules);
which uses the following
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*global define*/
define(
[],
function () {
"use strict";
return {
getRules: function() {
return {
'country_id': {
'required': true
}
};
}
};
}
from vendor/magento/module-offline-shipping/view/frontend/web/js/model/shipping-rates-validation-rules/freeshipping.js
to set up the rateRules in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rates-validation-rules.js
after this the vendor/magento/module-checkout/view/frontend/web/js/view/shipping.js module gets loaded, which on initialize calls:
shippingRatesValidator.initFields(fieldsetName);
from vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rates-validator.js
initFields: function (formPath) {
var self = this,
elements = shippingRatesValidationRules.getObservableFields();
if ($.inArray(postcodeElementName, elements) === -1) {
// Add postcode field to observables if not exist for zip code validation support
elements.push(postcodeElementName);
}
$.each(elements, function (index, field) {
uiRegistry.async(formPath + '.' + field)(self.doElementBinding.bind(self));
});
},
where
elements = shippingRatesValidationRules.getObservableFields();
uses the previously set up rate rules to get the fields to observe
it then adds the postcode fields if it is not set up yet and calls doElementBinding method on each element which calls this.bindHandler, which has the following:
element.on('value', function () {
clearTimeout(self.validateAddressTimeout);
self.validateAddressTimeout = setTimeout(function () {
if (self.postcodeValidation()) {
self.validateFields();
}
}, delay);
});
which calls self.validateFields();
validateFields: function () {
var addressFlat = addressConverter.formDataProviderToFlatData(
this.collectObservedData(),
'shippingAddress'
),
address;
if (this.validateAddressData(addressFlat)) {
address = addressConverter.formAddressDataToQuoteAddress(addressFlat);
selectShippingAddress(address);
}
},
which calls selectShippingAddress(address); which in turn sets the shippingAddress observerable.
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*global define*/
define(
[
'Magento_Checkout/js/model/quote'
],
function(quote) {
'use strict';
return function(shippingAddress) {
quote.shippingAddress(shippingAddress);
};
}
);
+1 for useful information, but this doesn't explain what triggers the observable on the shipping address object. Are there blur events on the front end fields that update the quote object -- other observables? Something else?
– Alan Storm
Nov 13 '16 at 22:12
@AlanStorm updated my answer
– Martijn Schot
Nov 15 '16 at 22:22
Thanks @martijn, marking this as best for now. I've been working on my own version and (as you seem to understand) a single Stack Overflow answer isn't going to do it.
– Alan Storm
Nov 16 '16 at 22:11
And my version of same, for anyone that's interested in a different path magento-quickies.alanstorm.com/post/153277368585/…
– Alan Storm
Nov 16 '16 at 23:33
Hi @alan,@Martjin ->example.com/rest/default/V1/carts/mine/… //sometime url not loading proper on cart estimation summary due to js issue so can we load it hardly even there are some JS issues in Console?If not then in which file can we check url return data so can debug properly?
– akgola
Sep 4 '17 at 6:52
|
show 1 more comment
in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rate-service.js:21 there is a subscribe to the shipping address observerable quote.shippingAddress.
quote.shippingAddress.subscribe(function () {
var type = quote.shippingAddress().getType();
if (processors[type]) {
processors[type].getRates(quote.shippingAddress());
} else {
processors.default.getRates(quote.shippingAddress());
}
});
In the callback funtion this calls to the getRates function in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rate-processor/new-address.js
getRates does an ajax call using the url build via the getUrlForEstimationShippingMethodsForNewAddress method you mentioned in your question and uses the result to update the rateRegistry and sets the shipping rates on the shippingRates observerable of the shipping service.
getRates: function (address) {
shippingService.isLoading(true);
var cache = rateRegistry.get(address.getCacheKey()),
serviceUrl = resourceUrlManager.getUrlForEstimationShippingMethodsForNewAddress(quote),
payload = JSON.stringify({
address: {
'street': address.street,
'city': address.city,
'region_id': address.regionId,
'region': address.region,
'country_id': address.countryId,
'postcode': address.postcode,
'email': address.email,
'customer_id': address.customerId,
'firstname': address.firstname,
'lastname': address.lastname,
'middlename': address.middlename,
'prefix': address.prefix,
'suffix': address.suffix,
'vat_id': address.vatId,
'company': address.company,
'telephone': address.telephone,
'fax': address.fax,
'custom_attributes': address.customAttributes,
'save_in_address_book': address.saveInAddressBook
}
}
);
if (cache) {
shippingService.setShippingRates(cache);
shippingService.isLoading(false);
} else {
storage.post(
serviceUrl, payload, false
).done(
function (result) {
rateRegistry.set(address.getCacheKey(), result);
shippingService.setShippingRates(result);
}
).fail(
function (response) {
shippingService.setShippingRates([]);
errorProcessor.process(response);
}
).always(
function () {
shippingService.isLoading(false);
}
);
}
}
The above show how the shipping methods get updated below will show how the quote.shippingAddres.subscribe is triggered:
The short version
Each shipping method has validation rules set against some of the shipping fields, these fields plus the postcode fields are observered via the knockoutjs 'value' binding and once this is triggered it updates the shipping address and this in turn as mentioned previously updates the shipping methods.
The long version
I will now explain the long version looking at the free shipping method, as this seems to be the same for all other included shipping methods.
on page load The view component Magento_OfflineShipping/js/view/shipping-rates-validation/freeshipping gets loaded via vendor/magento/module-offline-shipping/view/frontend/layout/checkout_index_index.xml
This makes a call to
defaultShippingRatesValidationRules.registerRules('freeshipping', freeshippingShippingRatesValidationRules);
which uses the following
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*global define*/
define(
[],
function () {
"use strict";
return {
getRules: function() {
return {
'country_id': {
'required': true
}
};
}
};
}
from vendor/magento/module-offline-shipping/view/frontend/web/js/model/shipping-rates-validation-rules/freeshipping.js
to set up the rateRules in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rates-validation-rules.js
after this the vendor/magento/module-checkout/view/frontend/web/js/view/shipping.js module gets loaded, which on initialize calls:
shippingRatesValidator.initFields(fieldsetName);
from vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rates-validator.js
initFields: function (formPath) {
var self = this,
elements = shippingRatesValidationRules.getObservableFields();
if ($.inArray(postcodeElementName, elements) === -1) {
// Add postcode field to observables if not exist for zip code validation support
elements.push(postcodeElementName);
}
$.each(elements, function (index, field) {
uiRegistry.async(formPath + '.' + field)(self.doElementBinding.bind(self));
});
},
where
elements = shippingRatesValidationRules.getObservableFields();
uses the previously set up rate rules to get the fields to observe
it then adds the postcode fields if it is not set up yet and calls doElementBinding method on each element which calls this.bindHandler, which has the following:
element.on('value', function () {
clearTimeout(self.validateAddressTimeout);
self.validateAddressTimeout = setTimeout(function () {
if (self.postcodeValidation()) {
self.validateFields();
}
}, delay);
});
which calls self.validateFields();
validateFields: function () {
var addressFlat = addressConverter.formDataProviderToFlatData(
this.collectObservedData(),
'shippingAddress'
),
address;
if (this.validateAddressData(addressFlat)) {
address = addressConverter.formAddressDataToQuoteAddress(addressFlat);
selectShippingAddress(address);
}
},
which calls selectShippingAddress(address); which in turn sets the shippingAddress observerable.
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*global define*/
define(
[
'Magento_Checkout/js/model/quote'
],
function(quote) {
'use strict';
return function(shippingAddress) {
quote.shippingAddress(shippingAddress);
};
}
);
in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rate-service.js:21 there is a subscribe to the shipping address observerable quote.shippingAddress.
quote.shippingAddress.subscribe(function () {
var type = quote.shippingAddress().getType();
if (processors[type]) {
processors[type].getRates(quote.shippingAddress());
} else {
processors.default.getRates(quote.shippingAddress());
}
});
In the callback funtion this calls to the getRates function in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rate-processor/new-address.js
getRates does an ajax call using the url build via the getUrlForEstimationShippingMethodsForNewAddress method you mentioned in your question and uses the result to update the rateRegistry and sets the shipping rates on the shippingRates observerable of the shipping service.
getRates: function (address) {
shippingService.isLoading(true);
var cache = rateRegistry.get(address.getCacheKey()),
serviceUrl = resourceUrlManager.getUrlForEstimationShippingMethodsForNewAddress(quote),
payload = JSON.stringify({
address: {
'street': address.street,
'city': address.city,
'region_id': address.regionId,
'region': address.region,
'country_id': address.countryId,
'postcode': address.postcode,
'email': address.email,
'customer_id': address.customerId,
'firstname': address.firstname,
'lastname': address.lastname,
'middlename': address.middlename,
'prefix': address.prefix,
'suffix': address.suffix,
'vat_id': address.vatId,
'company': address.company,
'telephone': address.telephone,
'fax': address.fax,
'custom_attributes': address.customAttributes,
'save_in_address_book': address.saveInAddressBook
}
}
);
if (cache) {
shippingService.setShippingRates(cache);
shippingService.isLoading(false);
} else {
storage.post(
serviceUrl, payload, false
).done(
function (result) {
rateRegistry.set(address.getCacheKey(), result);
shippingService.setShippingRates(result);
}
).fail(
function (response) {
shippingService.setShippingRates([]);
errorProcessor.process(response);
}
).always(
function () {
shippingService.isLoading(false);
}
);
}
}
The above show how the shipping methods get updated below will show how the quote.shippingAddres.subscribe is triggered:
The short version
Each shipping method has validation rules set against some of the shipping fields, these fields plus the postcode fields are observered via the knockoutjs 'value' binding and once this is triggered it updates the shipping address and this in turn as mentioned previously updates the shipping methods.
The long version
I will now explain the long version looking at the free shipping method, as this seems to be the same for all other included shipping methods.
on page load The view component Magento_OfflineShipping/js/view/shipping-rates-validation/freeshipping gets loaded via vendor/magento/module-offline-shipping/view/frontend/layout/checkout_index_index.xml
This makes a call to
defaultShippingRatesValidationRules.registerRules('freeshipping', freeshippingShippingRatesValidationRules);
which uses the following
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*global define*/
define(
[],
function () {
"use strict";
return {
getRules: function() {
return {
'country_id': {
'required': true
}
};
}
};
}
from vendor/magento/module-offline-shipping/view/frontend/web/js/model/shipping-rates-validation-rules/freeshipping.js
to set up the rateRules in vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rates-validation-rules.js
after this the vendor/magento/module-checkout/view/frontend/web/js/view/shipping.js module gets loaded, which on initialize calls:
shippingRatesValidator.initFields(fieldsetName);
from vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rates-validator.js
initFields: function (formPath) {
var self = this,
elements = shippingRatesValidationRules.getObservableFields();
if ($.inArray(postcodeElementName, elements) === -1) {
// Add postcode field to observables if not exist for zip code validation support
elements.push(postcodeElementName);
}
$.each(elements, function (index, field) {
uiRegistry.async(formPath + '.' + field)(self.doElementBinding.bind(self));
});
},
where
elements = shippingRatesValidationRules.getObservableFields();
uses the previously set up rate rules to get the fields to observe
it then adds the postcode fields if it is not set up yet and calls doElementBinding method on each element which calls this.bindHandler, which has the following:
element.on('value', function () {
clearTimeout(self.validateAddressTimeout);
self.validateAddressTimeout = setTimeout(function () {
if (self.postcodeValidation()) {
self.validateFields();
}
}, delay);
});
which calls self.validateFields();
validateFields: function () {
var addressFlat = addressConverter.formDataProviderToFlatData(
this.collectObservedData(),
'shippingAddress'
),
address;
if (this.validateAddressData(addressFlat)) {
address = addressConverter.formAddressDataToQuoteAddress(addressFlat);
selectShippingAddress(address);
}
},
which calls selectShippingAddress(address); which in turn sets the shippingAddress observerable.
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*global define*/
define(
[
'Magento_Checkout/js/model/quote'
],
function(quote) {
'use strict';
return function(shippingAddress) {
quote.shippingAddress(shippingAddress);
};
}
);
edited Aug 26 '17 at 2:46
Mehdi
609721
609721
answered Nov 13 '16 at 11:13
Martijn SchotMartijn Schot
675513
675513
+1 for useful information, but this doesn't explain what triggers the observable on the shipping address object. Are there blur events on the front end fields that update the quote object -- other observables? Something else?
– Alan Storm
Nov 13 '16 at 22:12
@AlanStorm updated my answer
– Martijn Schot
Nov 15 '16 at 22:22
Thanks @martijn, marking this as best for now. I've been working on my own version and (as you seem to understand) a single Stack Overflow answer isn't going to do it.
– Alan Storm
Nov 16 '16 at 22:11
And my version of same, for anyone that's interested in a different path magento-quickies.alanstorm.com/post/153277368585/…
– Alan Storm
Nov 16 '16 at 23:33
Hi @alan,@Martjin ->example.com/rest/default/V1/carts/mine/… //sometime url not loading proper on cart estimation summary due to js issue so can we load it hardly even there are some JS issues in Console?If not then in which file can we check url return data so can debug properly?
– akgola
Sep 4 '17 at 6:52
|
show 1 more comment
+1 for useful information, but this doesn't explain what triggers the observable on the shipping address object. Are there blur events on the front end fields that update the quote object -- other observables? Something else?
– Alan Storm
Nov 13 '16 at 22:12
@AlanStorm updated my answer
– Martijn Schot
Nov 15 '16 at 22:22
Thanks @martijn, marking this as best for now. I've been working on my own version and (as you seem to understand) a single Stack Overflow answer isn't going to do it.
– Alan Storm
Nov 16 '16 at 22:11
And my version of same, for anyone that's interested in a different path magento-quickies.alanstorm.com/post/153277368585/…
– Alan Storm
Nov 16 '16 at 23:33
Hi @alan,@Martjin ->example.com/rest/default/V1/carts/mine/… //sometime url not loading proper on cart estimation summary due to js issue so can we load it hardly even there are some JS issues in Console?If not then in which file can we check url return data so can debug properly?
– akgola
Sep 4 '17 at 6:52
+1 for useful information, but this doesn't explain what triggers the observable on the shipping address object. Are there blur events on the front end fields that update the quote object -- other observables? Something else?
– Alan Storm
Nov 13 '16 at 22:12
+1 for useful information, but this doesn't explain what triggers the observable on the shipping address object. Are there blur events on the front end fields that update the quote object -- other observables? Something else?
– Alan Storm
Nov 13 '16 at 22:12
@AlanStorm updated my answer
– Martijn Schot
Nov 15 '16 at 22:22
@AlanStorm updated my answer
– Martijn Schot
Nov 15 '16 at 22:22
Thanks @martijn, marking this as best for now. I've been working on my own version and (as you seem to understand) a single Stack Overflow answer isn't going to do it.
– Alan Storm
Nov 16 '16 at 22:11
Thanks @martijn, marking this as best for now. I've been working on my own version and (as you seem to understand) a single Stack Overflow answer isn't going to do it.
– Alan Storm
Nov 16 '16 at 22:11
And my version of same, for anyone that's interested in a different path magento-quickies.alanstorm.com/post/153277368585/…
– Alan Storm
Nov 16 '16 at 23:33
And my version of same, for anyone that's interested in a different path magento-quickies.alanstorm.com/post/153277368585/…
– Alan Storm
Nov 16 '16 at 23:33
Hi @alan,@Martjin ->example.com/rest/default/V1/carts/mine/… //sometime url not loading proper on cart estimation summary due to js issue so can we load it hardly even there are some JS issues in Console?If not then in which file can we check url return data so can debug properly?
– akgola
Sep 4 '17 at 6:52
Hi @alan,@Martjin ->example.com/rest/default/V1/carts/mine/… //sometime url not loading proper on cart estimation summary due to js issue so can we load it hardly even there are some JS issues in Console?If not then in which file can we check url return data so can debug properly?
– akgola
Sep 4 '17 at 6:52
|
show 1 more comment
To force reloading of shipping methods try,
define(
[
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/shipping-rate-processor/new-address',
'Magento_Checkout/js/model/shipping-rate-processor/customer-address',
'Magento_Checkout/js/model/shipping-rate-registry'
],
function (quote, defaultProcessor, customerAddressProcessor, rateRegistry) {
'use strict';
var processors = [];
rateRegistry.set(quote.shippingAddress().getCacheKey(), null);
processors.default = defaultProcessor;
processors['customer-address'] = customerAddressProcessor;
var type = quote.shippingAddress().getType();
if (processors[type]) {
processors[type].getRates(quote.shippingAddress());
} else {
processors.default.getRates(quote.shippingAddress());
}
}
);
not post the updated address when I use this one code.
– Magento2 Devloper
Mar 7 '18 at 11:22
I did reload the the shipping-method-item.html for me with this code.
– Juliano Vargas
May 23 '18 at 11:27
add a comment |
To force reloading of shipping methods try,
define(
[
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/shipping-rate-processor/new-address',
'Magento_Checkout/js/model/shipping-rate-processor/customer-address',
'Magento_Checkout/js/model/shipping-rate-registry'
],
function (quote, defaultProcessor, customerAddressProcessor, rateRegistry) {
'use strict';
var processors = [];
rateRegistry.set(quote.shippingAddress().getCacheKey(), null);
processors.default = defaultProcessor;
processors['customer-address'] = customerAddressProcessor;
var type = quote.shippingAddress().getType();
if (processors[type]) {
processors[type].getRates(quote.shippingAddress());
} else {
processors.default.getRates(quote.shippingAddress());
}
}
);
not post the updated address when I use this one code.
– Magento2 Devloper
Mar 7 '18 at 11:22
I did reload the the shipping-method-item.html for me with this code.
– Juliano Vargas
May 23 '18 at 11:27
add a comment |
To force reloading of shipping methods try,
define(
[
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/shipping-rate-processor/new-address',
'Magento_Checkout/js/model/shipping-rate-processor/customer-address',
'Magento_Checkout/js/model/shipping-rate-registry'
],
function (quote, defaultProcessor, customerAddressProcessor, rateRegistry) {
'use strict';
var processors = [];
rateRegistry.set(quote.shippingAddress().getCacheKey(), null);
processors.default = defaultProcessor;
processors['customer-address'] = customerAddressProcessor;
var type = quote.shippingAddress().getType();
if (processors[type]) {
processors[type].getRates(quote.shippingAddress());
} else {
processors.default.getRates(quote.shippingAddress());
}
}
);
To force reloading of shipping methods try,
define(
[
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/shipping-rate-processor/new-address',
'Magento_Checkout/js/model/shipping-rate-processor/customer-address',
'Magento_Checkout/js/model/shipping-rate-registry'
],
function (quote, defaultProcessor, customerAddressProcessor, rateRegistry) {
'use strict';
var processors = [];
rateRegistry.set(quote.shippingAddress().getCacheKey(), null);
processors.default = defaultProcessor;
processors['customer-address'] = customerAddressProcessor;
var type = quote.shippingAddress().getType();
if (processors[type]) {
processors[type].getRates(quote.shippingAddress());
} else {
processors.default.getRates(quote.shippingAddress());
}
}
);
answered Jan 2 '18 at 20:59
Renon StewartRenon Stewart
12.1k12044
12.1k12044
not post the updated address when I use this one code.
– Magento2 Devloper
Mar 7 '18 at 11:22
I did reload the the shipping-method-item.html for me with this code.
– Juliano Vargas
May 23 '18 at 11:27
add a comment |
not post the updated address when I use this one code.
– Magento2 Devloper
Mar 7 '18 at 11:22
I did reload the the shipping-method-item.html for me with this code.
– Juliano Vargas
May 23 '18 at 11:27
not post the updated address when I use this one code.
– Magento2 Devloper
Mar 7 '18 at 11:22
not post the updated address when I use this one code.
– Magento2 Devloper
Mar 7 '18 at 11:22
I did reload the the shipping-method-item.html for me with this code.
– Juliano Vargas
May 23 '18 at 11:27
I did reload the the shipping-method-item.html for me with this code.
– Juliano Vargas
May 23 '18 at 11:27
add a comment |
You can first call selectShippingAddressAction. That will set your shipping address to quote.shippingAddress. After that you can setSelectedShippingAddress to checkoutData.
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;
}
});
});
Shipping rates are recalculated automatically 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.
If you want 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.
I defined shipping-rate-service.js in dependencies for it to trigger getRates methods because otherwise getRates method is called before our needed shipping address is set to quote. That's why without this dependency our shipping rates won't be estimated and there will be no AJAX request to estimate-shipping-methods
add a comment |
You can first call selectShippingAddressAction. That will set your shipping address to quote.shippingAddress. After that you can setSelectedShippingAddress to checkoutData.
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;
}
});
});
Shipping rates are recalculated automatically 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.
If you want 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.
I defined shipping-rate-service.js in dependencies for it to trigger getRates methods because otherwise getRates method is called before our needed shipping address is set to quote. That's why without this dependency our shipping rates won't be estimated and there will be no AJAX request to estimate-shipping-methods
add a comment |
You can first call selectShippingAddressAction. That will set your shipping address to quote.shippingAddress. After that you can setSelectedShippingAddress to checkoutData.
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;
}
});
});
Shipping rates are recalculated automatically 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.
If you want 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.
I defined shipping-rate-service.js in dependencies for it to trigger getRates methods because otherwise getRates method is called before our needed shipping address is set to quote. That's why without this dependency our shipping rates won't be estimated and there will be no AJAX request to estimate-shipping-methods
You can first call selectShippingAddressAction. That will set your shipping address to quote.shippingAddress. After that you can setSelectedShippingAddress to checkoutData.
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;
}
});
});
Shipping rates are recalculated automatically 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.
If you want 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.
I defined shipping-rate-service.js in dependencies for it to trigger getRates methods because otherwise getRates method is called before our needed shipping address is set to quote. That's why without this dependency our shipping rates won't be estimated and there will be no AJAX request to estimate-shipping-methods
edited 3 mins ago
answered 12 mins ago
transversustransversus
212
212
add a comment |
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f145483%2fwhat-programmatically-triggers-magento-2s-shipping-rates-to-update%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown