drop-down-menuyii2

Yii2 DropDownList from Database Disable Option


Looking for a way to dynamically set a dropdownlist option as disabled.

In my controller, I dynamically add 'Fully Booked' to my description. My data returned in $accommodationList could look something like this:

'1' => 'Protea Hotel'
'18' => 'Sun Hotel - Fully Booked'
'22' => 'Safari Lodge'

In above case, I don't want my user to select 'Sun Hotel'. I cannot use the id's (1, 18, 22) because while the admin is setting up the system (before users start using it) the admin might add and delete accommodation rows, thus the database will auto generate the id's. I am trying to do something like this.

<?php
echo $form->field($model, 'accommodation_id')->dropdownList(
     $accommodationList,
     ['options' => function ($label, $value) {
        if (str_contains($label, 'Fully Booked')) {
           return "<option value='".$value."' disabled='disabled'>".$label."</option>";
        }
        return "<option value='".$value."'>".$label."</option>";
     }]
     )->label(false);
?>

Which I am hoping will give me something like this:

<option value='1'>Protea Hotel</option>
<option value='18' disbaled='disabled'>Sun Hotel - Fully Booked</option>
<option value='22'>Safari Lodge</option>

Solution

  • The 'options' key of $options parameter for dropdown list doesn't support callbacks. But you can pass array of options for different values in format like this:

    'key' => ['disabled' => true],
    'another-key' => [ ... ],
    ...
    

    So you need to prepare the options beforehand. For example like this:

    $options = [];
    foreach($accommodationList as $key => $label) {
        if (str_contains($label, 'Fully Booked')) {
            $options[$key] = ['disabled' => true];
        }
    }
    echo $form->field($model, 'accommodation_id')->dropdownList(
        $accommodationList,
        ['options' => $options]
    )->label(false);