Skip to content

How to disable options in a Magento 2 custom select field without using setTimeout?

I have a custom select field in my Magento 2 form and I’m loading options dynamically. The goal is to disable specific options based on a condition (option.is_disabled). The current implementation works, but I’m using setTimeout to apply the disabling logic after the options are loaded. Here’s my current solution:

<field name="locale_code" sortOrder="10" formElement="select" component="Vendor_Module/js/form/element/select">
    <settings>
        <dataType>select</dataType>
        <label translate="true">Locale</label>
        <dataScope>data.locale_code</dataScope>
        <validation>
            <rule name="required-entry" xsi:type="boolean">true</rule>
        </validation>
    </settings>
    <formElements>
        <select>
            <settings>
                <options class="VendorModuleUiComponentListingColumnLocaleOptions"/>
            </settings>
        </select>
    </formElements>
</field>
define([
    'Magento_Ui/js/form/element/select'
], function (Select) {
    'use strict';

    return Select.extend({
        initialize: function () {
            this._super();

            setTimeout(() => {
                this.options().forEach((option) => {
                    if (option.is_disabled) {
                        let element = document.querySelector(`[value=${option.value}]`);
                        element.disabled = true;
                    }
                });
            }, 2000);

            return this;
        }
    });
});

While this implementation works, I’m using setTimeout to delay the execution until the options are loaded. This is not an ideal solution. I’m looking for a more reliable or “Magento 2” way to disable the options after they’ve been rendered, without relying on setTimeout.

Does anyone know the correct approach to disable specific options in a Magento 2 custom select field once they are rendered?