A
A
Albert Tobacco2015-07-31 15:48:29
Yii
Albert Tobacco, 2015-07-31 15:48:29

Best way to get dropdown items in Yii2?

There is a table with the fields `id`, `name`, `another`, `fields`....
I want to get the view array through the ActiveRecord interface:
[id => name, id => name]
I know how to get the view array:

[ id => [ name => 'value' ] , id => [ name => 'value' ]  ]

To do this, I can write
Model::find->all()->indexBy('id');
But I want the value to be a specific field and not an array key value

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LAV45, 2015-08-02
@bighoc

public static function getList()
    {
        return static::find()
            ->select(['name', 'id'])
            ->indexBy('id')
            ->asArray()
            ->column();
    }

asArray() - returns data as a regular array, helps to save memory and works out a little faster.
column() - returns the first column name because it will be the first select(['name', 'id'])
indexBy('id') - arranges the correct keys

V
Vit, 2015-07-31
@fornit1917

I run it through ArrayHelper::map.
ArrayHelper::map($models, 'id', 'name') will give you what you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question