I took Sébastien Gicquel answer and tweaked it a little, so you can define disabled options when building form.
It is for Drupal 10 but I think it is so simple that should work on other Drupal versions as well.
In JS file (I created small library mymodule\forms
to customize forms) create code to disable certain options.
$(".select-options-disabled").each(function(){
let selectNode = $(this);
let optionsIdxs = selectNode.data('options-disabled').split(",");
$.each(optionsIdxs, function(_i, idx){
selectNode.find('option:nth-child(' + idx + ')').attr("disabled", "true");
});
});
Then in any buildForm function when you want to create select with disabled options just add two attributes to it. Class .select-options-disabled
, and data-options-disabled
as comma seperated list of options to disable in given select. For example:
$form['my_options'] = array(
'#type' => 'select',
'#options' => $options,
'#attributes' => [
'class' => ['select-options-disabled'],
'data-options-disabled' => '1,3',
],
);
Remember to add your JS file in my case it is my library
$form['#attached']['library'][] = 'mymodule/forms';
Also keep in mind that CSS nth-child selector starts from 1, not 0 therefore to disable first option in select add "1" not "0" :)
Still I wish there would be better option to do this, if there is please add comment here.