Creating an array using find() with special values

Hi guys, it’s me again.

My intention is to get special values (id and verwendungszweck) of an array in order to create dropdownBox like this:





<?=

$form->field($value, "[{$i}]id_kontakt_verwendungszweck")

->dropDownList([1 => 'Festnetz',17 => 'Festnetz privat', 18 => 'Festnetz geschäftlich', 15 => 'Mobil privat', 16 => 'Mobil geschäftlich'], ['prompt' => '']);

?> 



In Formular, I intend to use dropDownList like this:





<?=

$form->field($value, "[{$i}]id_kontakt_verwendungszweck")->dropDownList([$DropDownTelefon], ['prompt' => '']);

?>  



I try like this, but it’s not the same as defining DropDownList statically(Look at my attachments,please). DropDown_IS will show, as it is ,actually, DropDown_Soll will show, as it should be. The sequence of values is unimportant!





$lKontaktVerwendungszweck = LKontaktVerwendungszweck::find()->where(['id_kontakt_art' => 1, 'id_person_art' => 1])->all();

$DropDownTelefon = array();

$i = 0;

foreach ($lKontaktVerwendungszweck as $kontakt) {

    $id = $kontakt->id;

    $zweck = $kontakt->verwendungszweck;

    $DropDownTelefon[$i] = [

 		$id => $zweck

    ];

    $i++;

}



Any ideas how to achieve my intention?

P.S.: I’m not able to use SELECT2 widget of kartik, unfortunately!

I just dealt with this very problem today. Your array to populate the dropdown needs to be like:





return [

'id1' => 'attribute1',

'id2' => 'attribute2',

...

];



To create these for my drop downs I use a model method. Let’s say I want the keys to be the id’s and the values to be some other model attribute.




//view of form

<?= $form->field($model, 'attribute')->dropDownList($model->getDropDownArray()); ?>

//in the model

public function getDropDownArray()

{

  $modelname = Modelname::find()

  ->where(['someattribute'=>$somevariable]) //optional if conditions needed to limit data

  ->all(); 

  $items = array();

  foreach($modelname as $model){

  $items[$model->id] = $model->attribute

  }

  return $items;

}



This way the keys of the array $items are the ids and the values of the array are all the user sees.

Works Great!

Thx a lot for ur solution. This solution is much smarter as mine and will give me values as intended.

I gave u reputation points for ur code…!

This thread can be closed as succesfully solved