简体   繁体   中英

zf2 form disable select option(s)

Is it possible to disable the options in a select element?

I have a form with a select element that by default has a lot of options available. During form creation, depending on information retrieved from the database, i would like to disable certain options.

Some research came up with $form->get('selectElement')->setAttribute("disabled", array(0, 1, 2)); ...which should disable the first 3 options, but unfortunately does not.

You must use the setAttribute() method to set the attributes of your select element, not its options. For this, you should use setValueOptions() :

$myOptions = $form->get('selectElement')->getValueOptions();
foreach ([0, 1, 2] as $value) {
    $myOptions [$value]['disabled'] = true ;
}
$form->get('selectElement')->setValueOptions($myOptions);

$myOptions must be an array of options:

[
    [
        'label' => 'My first option',
        'disabled' => false,
        'value' => 1
    ],
    [
        'label' => '2nd option',
        'disabled' => false,
        'value' => 2
    ],
    [
        'label' => '3rd option disabled',
        'disabled' => true,
        'value' => 3
    ],
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM