Question

I'm working on the checkout in Magento 2 (2.2.5). And I constantly have the issue in JavaScript that I don't know when a field is loaded. So if I need the input of country_id field for function I can't get it unless I place a setTimeout around it.

There must be a better solution, right?

Was it helpful?

Solution

I was able to achieve this using uicomponent. You can refer the below example

define([
    'underscore',
    'uiRegistry',
    'Magento_Ui/js/form/element/select',
    'Magento_Ui/js/modal/modal'
], function (_, uiRegistry, select, modal) {
    'use strict';

    return select.extend({

        dependentFields: [
               'sales_rule_form.sales_rule_form.actions.my_new_field1',
               'sales_rule_form.sales_rule_form.actions.my_new_field2',
        ],
        initialize: function() {
            this._super();

            uiRegistry.promise(this.dependentFields).done(_.bind(function(){
                this.enableDisableFields(this.getFieldsToShow(this.value()));
            }, this));
        },
        onUpdate: function (value) {            
            this.enableDisableFields(this.getFieldsToShow(value));
            return this._super();
        },
        enableDisableFields: function (fields) {
            uiRegistry.get(this.dependentFields, function () {
                _.each(arguments, function(argument){
                    (_.contains(fields, argument['index']))?
                        argument['show']():argument['hide']();
                });
            });
        },
        getFieldsToShow: function(type){
            return ['my_new_field2'];
        }
    });
});

In above example I am extending select for dependency and uiRegistry.promise(this.dependentFields) It first check if the fields are loaded the It binds the methods I require to execute.

You can also refer jQuery Promise

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top