0

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="Vendor\Module\Ui\Component\Listing\Column\LocaleOptions"/> </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?

1 Answer 1

0

Yes! Instead of using setTimeout, you should observe changes in the options array and disable options when they are updated. Magento 2 uses Knockout.js, so you can leverage this.options.subscribe to react to changes dynamically.

Updated Code

define([ 'Magento_Ui/js/form/element/select', 'ko' ], function (Select, ko) { 'use strict'; return Select.extend({ initialize: function () { this._super(); // Subscribe to changes in options and apply disabling logic this.options.subscribe(this.disableOptions.bind(this)); return this; }, disableOptions: function (options) { options.forEach((option) => { if (option.is_disabled) { let element = document.querySelector(`[value="${option.value}"]`); if (element) { element.disabled = true; } } }); } }); }); 

Instead of setTimeout, we subscribe to this.options so that our function triggers as soon as the options are loaded. This ensures that disabling happens at the right time without arbitrary delays. It follows Magento’s Knockout.js principles, making it a more reliable solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.