John Crest
John Crest

Reputation: 261

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.

Upvotes: 2

Views: 1089

Answers (1)

Al Foиce    ѫ
Al Foиce ѫ

Reputation: 4315

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);

$myOptionsmust 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
    ],
]

Upvotes: 1

Related Questions