1

I have written a custom shipping module, then I want to change custom shipping methods when country and post code changes. I heard there is a method call js mixin. any one have idea about it, need help to do it, thanks

3

1 Answer 1

9

You have to add mixin for shipping-rates-validation-rules

Add mixins in requirejs-config.js

app/code/Vendor/ShippingModule/view/frontend/requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_Checkout/js/model/shipping-rates-validation-rules': {
                'Vendor_ShippingModule/js/model/shipping-rates-validation-rules-mixin': true
            }
        }
    }
};

Now create shipping-rates-validation-rules-mixin.js

app/code/Vendor/ShippingModule/view/frontend/web/js/model/shipping-rates-validation-rules-mixin.js

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

    return function (targetFunction) {
        targetFunction.getObservableFields = function () {
            var self = this,
                observableFields = [];

            $.each(self.getRules(), function (carrier, fields) {
                $.each(fields, function (field) {
                    if (observableFields.indexOf(field) === -1) {
                        observableFields.push(field);
                    }
                });
            });

            observableFields.push('country_id'); // Load shipping method on Country chnage
            observableFields.push('postcode'); // Load shipping method on Postcode chnage
            //observableFields.push('telephone'); // Load shipping method on Phone Number chnage
            //observableFields.push('city'); // Load shipping method on City chnage


            return observableFields;
        }

        return targetFunction;
    };
});

Now run this commands:

php bin/magento setup:static-content:deploy

php bin/magento cache:flush

If js or html changes not display refer this answer: https://magento.stackexchange.com/a/208844/35758

7
  • I have add you code, but nothing happened :(
    – Lasantha
    May 3, 2018 at 16:45
  • can you describe how this code works. self.getRules() returns empty.
    – Lasantha
    May 3, 2018 at 17:22
  • 1
    Working on M2.2.5
    – Adnan
    Sep 26, 2018 at 20:19
  • 1
    Worked like a charm! Thanks a lot
    – jackcar
    Apr 10, 2019 at 21:54
  • 1
    Great. Worked without any single problem.
    – Nayem323
    Feb 12, 2020 at 7:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.