0

I am adding custom field on Magento 2 checkout shipping address. It's a hidden input. The value should be automatically updated based on another custom field which is a select (populated from ajax response data), using its option text/label. How can I "link" between input value and selected option text?

In my current custom component for the select, it already export the value to input

            exports: {
            value: '${ $.provider }:shippingAddress.custom_attributes.subdstrict:value'
        }

But it sends the selected value instead of the text. how to send the selected option text instead?

1
  • Teja, did you find any solution for this. Commented Aug 28, 2019 at 8:43

1 Answer 1

0

I managed to achieve this using this code

    return Select.extend({
    defaults: {
        skipValidation: false,
        exports: {
            // Don: any change to subdisrict_id dropdown will "send" notifcation to subdistrict input
            selectedSubdistrictName: '${ $.provider }:${ $.customScope }.custom_attributes.subdistrict:value'
        }
    },

    /**
     * @inheritdoc
     */
    initObservable: function () {
        this._super()
            .observe(['selectedSubdistrictName']);

        return this;
    },

    /**
     * Filters 'initialOptions' property by 'field' and 'value' passed,
     * calls 'setOptions' passing the result to it
     *
     * @param {*} value
     * @param {String} field
     */
    initialize : function(){
        var self = this;
        this._super();
        self.value.subscribe(function(value){
            self.selectedSubdistrictName( self.getPreview() );
        }, this)
    },

filter: function (value, field) {
        if(value) {
            var thisField = this;

            $.ajax({
                type: 'GET',
                url: '/rest/V1/fabelio-directory/subdistricts/' + value,
                dataType: 'json',
                success: function(data) {
                    // rename keys
                    var options = [];
                    var option = {};
                    for(var i = 0; i < data.length; i++) {
                        option = {
                            'value': data[i].subdistrict_id,
                            'label': data[i].name
                        };
                        options.push(option);

                    }
                    thisField.setOptions(options);
                },
                error: function() {
                },
                complete: function() {
                }
            });
        }

    }

});
});

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.