Search code examples
formsyii2dropdown

Html::dropDownList() with preselected values


It is necessary to pre-select the values in the dropdown. But for some reason, the values do not predispose. How to fix it?

All items - $items:

array(1) {
  [1]=>
  string(29) "Санкт-Петербург"
}

$selectedItems:

array(1) {
  [1]=>
  string(29) "Санкт-Петербург"
}  

<?= Html::dropDownList('cities', $selectedItems, $items, ['class' => 'form-control', 'multiple' => true]) ?>

Solution

  • $selectedItem should contain only selected indexes.

    For example:

    $items[0] = 'A'; // preselected
    $items[1] = 'B';
    $items[2] = 'C'; // preselected
    
    $selectedItems = [0, 2];
    
    echo Html::dropDownList('cities', $selectedItems, $items, ['class' => 'form-control', 'multiple' => true]);