Difference between #202 and #203 of
Yii v2 snippet guide

Revision #203 has been created by rackycz on Jun 30, 2020, 11:17:58 PM with the memo:

FK DropDown
« previous (#202) next (#204) »

Changes

Title unchanged

Yii v2 snippet guide

Category unchanged

Tutorials

Yii version unchanged

2.0

Tags unchanged

tutorial,beginner,yii2

Content changed

[...]
],

// ...

```

 
**Drop down list for foreign-key column**
 
Do you need to specify for example currency using a predefined list, but your view contains only a simple text-input where you must manually enter currency_id from table Currency? 
 
 
Read how to enhance it. You only need models with predefined relations - this can be done using GII when relations are defined in MySQL. How to create relations [manually](https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#relational-data).
 
 
---
 
```php
 
use yii\helpers\ArrayHelper;
 
use app\models\Currency; // My example uses Currency model
 
 
$currencies = Currency::find()->asArray()->all();
 
 
// 'id' = the primary key column
 
// 'name' = the column with text to be dispalyed to user
 
// https://www.yiiframework.com/doc/api/2.0/yii-helpers-basearrayhelper#map()-detail
 
$currencies = ArrayHelper::map($currencies, 'id', 'name'); 
 
 
<?= $form->field($model, 'id_currency')->dropDownList($currencies) ?>
 
```
 
7 0
4 followers
Viewed: 252 289 times
Version: 2.0
Category: Tutorials
Written by: rackycz
Last updated by: rackycz
Created on: Sep 19, 2019
Last updated: 4 months ago
Update Article

Revisions

View all history