问题
Is it possible to make dropdown in Yii2 from two column in one row table like this:
I want dropdown list like this:
回答1:
You haven't provided any details of the model you are using for the dropdown so I will demonstrate the example with Phone model and the fields are id, phone, area_code, just for the sake of understanding.
This is the data for phone table:
+----+-------------+-----------+
| id | phone | area_code |
+----+-------------+-----------+
| 1 | 03214442021 | 021 |
| 2 | 03214452520 | 051 |
+----+-------------+-----------+
Now, if you are selecting a single row from the database and trying to list all the columns from the single row inside the drop-down you can use the array_filter to filter out all the attributes into an array and then assign that array to the drop-down options.
Although you can use the same approach and use array_filter inside the foreach if you are selecting all the rows from the table, the difference would be the layout of the drop down.
When selecting a single row you will get the drop-down as follows:
And if you are selecting all the rows from the table the dropdown will look like below:
In your controller, you can do the following:
For Single Row
public function actionPhone($id){
$model = Phone::findOne($id);
$rows = array_filter($model->attributes);
return $this->render('drop-down', ['rows' => $rows]);
}
For Multiple Rows
public function actionPhone(){
$phone = Phone::find()->all();
foreach ($phone as $model) {
$rows[] = array_filter($model->attributes);
}
return $this->render('drop-down', ['rows' => $rows]);
}
The view part remains the same for both of the cases above, inside your view where you are creating the drop-down assign the rows to the options.
You can build the dropdown using yii\helpers\Html or ActiveForm.
<?= yii\helpers\Html::dropDownList('my-options',null,$rows) ?>
Note: The dropdown option text is the value of the column and the dropdown option value is the column name. Means the first option in drop-down ['id'=>1] the id will be the value and 1 will be the text displayed for the option.
EDIT
If you need to use the value for both the option and text you might need to use \yii\helpers\ArrayHelper::map() where you can pass closure to the $from and $to means an anonymous function that way you can have the column value as key and value both like below:
Array(
[1]=>1,
[03214442021]=>03214442021 ,
[021]=>021
)
So change your action to the following:
public function actionPhone($id){
$model = Phone::findOne($id);
$rows=\yii\helpers\ArrayHelper::map(array_filter($model->attributes),function($item){
return $item;
},function($item){
return $item;
});
return $this->render('drop-down', ['rows' => $rows]);
}
来源:https://stackoverflow.com/questions/50764216/how-to-make-dropdown-in-yii2-from-one-record