dimis283
(Dimis283)
November 15, 2016, 2:25pm
1
I am trying to fill a drop-down menu with data from a query without success.
I use the code bellow,how can I fix it?
<?= $form->field($model, 'plan_id')->dropDownList([
yii\helpers\ArrayHelper::map(Yii::$app->db->createCommand('SELECT id,name FROM plans')
->queryAll(), 'id', 'name'),
['prompt' => 'Set plan'],
'options'=>[$pl=>['Selected'=>true]]]);?>
luiszg23
(Luis)
November 17, 2016, 4:50am
2
I think that is a bad practice, because the view shouldn’t call model data. You should use a model to return an array and next use this date in the view:
Model
public function listaEstados($esta_id = null){
$estados = ArrayHelper::map($this->find()->all(),'esta_id','esta_estado');
if(is_null($esta_id)){
return $estados;
}else{
return $estados[$esta_id];
}
}
Controller
return $this->render('_form', [
'model' => $model,
'estados' => $estados->listaestados(),
]);
View
<?= $form->field($model, 'tare_esta_id')->dropDownList($estados,array('prompt'=>Yii::t('app', 'Seleccione un estado'))) ?>
First idea to try to debug your code is passing a mockup instead the query to check wich part has the problem. Try the following:
<?= $form->field($model, ‘plan_id’)->dropDownList(
[
array(
'1'=>'A label',
'2'=>'Other label'
'3'=>'Another item label'),
[‘prompt’ => ‘Set plan’],
'options'=> [ $pl=> ['Selected'=>true] ]
]
);?>
If this works, then the problem is in the query.
The values of the array are converted to <option value="id">name</option>