What is the best practise to pass on an array variable from controller to view file


I have to create a dropDownList in view file.

The content of dropDownList is city array [‘id’ => ‘city_name’].

My list of cities is in database, because user can modify any city (delete or add new one).

So in controller, I create variable:

$cityArrayList = CityList::getCityList();

and pass on to view file:

return $this->render('index',['cityList' => $cityArrayList]);

In view file I create dropDownList with $cityList as a content:






            'options' => 


                    'class' => 'col-xs-12 col-sm-4 col-md-4 col-lg-4 required'





My question is: am I doing it correctly, or should I use


directly in dropDownList, like:


Which method is better, and don’t go out from MVC principles? To create array in controller and pass on to view file, or to take array directly in dropDownList? Thanks for answers.

I’d say you are doing it right.

However, you might find that calling CityList::getCityList() in the view file will save you some coding.

For example if you have a create and a update action, that both will load same view file, it makes more sense to call CityList::getCityList() in the view file because you don’t repeat the code in two places, that is, both actions.

personally i would go with second choice, i don’t care about what MVC has to say about this, but i do care about making my work easier.

Thank you very much for your answer.

You are not showing your getCityList method. Does it look like this:

  public static function getCityList()


        $droptions = CityList::find()->asArray()->all();

        return Arrayhelper::map($droptions, 'id', 'city_name');  


If you coded as a static function, you can use it without passing an instance of the model from the controller. Note: $droptions is just a local variable name, you can pick anything you want.

Alternatively, if you pass the model to view as $model, you can use the $model->cityList to call the dropdown list, using the magic get syntax, instead of CityList::getCityList().

@evercode - “$droptions”, clever :D

@twisted1919 Thank you.