Magento 2.1 – Update Shipping Rate on Providing Zipcode in Cart Page

magento-2.1magento2shipping-methods

In the UPS shipping method, when we type zip code the shipping rate will be automatically calculated based on the zip code provided. The same thing I have to customize in flatrate too. I have my custom function which returns the shipping rate on providing the zip code. I can call that function on providing the zip code in cart page (Summary Block). Please help me to write that code. I tried to find the ajax call running on typing the zip code. How can I add the same feature as in ups to flaterate. Anybody help please.

Best Answer

During checkout page initialization the checkout shipping-rates-validator registers all validators for shipping carriers.

When a customer fills inputs on the address form, the checkout js component triggers validators for available shipping carriers, these validators have rules with required fields and if required field is changed by the customer the checkout js component calls estimation-service, which gets available rates from the backend.

So, to proceed estimation-service call, when the customer changes zip code input, you need to specify validation rules in your own shipping validator.

Your custom shipping carrier should have two js components: shipping-rates-validator and shipping-rates-validation-rules and it might look like this (Custom_Shipping/view/frontend/web/js/model/shipping-rates-validation-rules.js):

define([], function () {
    'use strict';

    return {
        getRules: function () {
            return {
                'postcode': {
                    'required': true
                }
            };
        }
    };
});

And the rates validator (Custom_Shipping/view/frontend/web/js/model/shipping-rates-validator):

define([
    'jquery',
    'mageUtils',
    'Custom_Shipping/js/model/shipping-rates-validation-rules',
    'mage/translate'
], function ($, utils, validationRules, $t) {
    'use strict';

    return {
        validationErrors: [],
        validate: function (address) {
            var self = this;

            this.validationErrors = [];
            $.each(validationRules.getRules(), function (field, rule) {
                var message;

                if (rule.required && utils.isEmpty(address[field])) {
                    message = $t('Field ') + field + $t(' is required.');

                    self.validationErrors.push(message);
                }
            });

            return !Boolean(this.validationErrors.length);
        }
    };
});

Each time, when the customer will change zip code in address form input, the checkout js component will call estimation-service and your custom shipping provider can return rates based on provided zip code.