Reputation: 18316
I want to show a dropdown in a form in a Yii project with for items. I know I can use
echo $form->dropDownList($model,'element_id', $Options);
in _form.php view file.
Where is the best place to fulfill $options variable ? in which file ? view ? controller ?
Upvotes: 0
Views: 99
Reputation: 745
The current model is the best option for this purpose because _form.php
has access to the model and so you can get the data easily. While you can pass data from the controller to _form.php
, this is more work.
If you want to populate data from the database - for example, you want to show countries from a database table tbl_countries
- you can write a function in your model to load them:
/* Get all countries. */
public function getCountries(){
$allCountries = Countries::model()->findAll();
return CHtml::listData($allCountries, "id", "name")
}
This will give you an array with the id numbers as keys and the country names as values. You can then call this function from your view file:
echo $form->dropDownList($model,'element_id', $model->countries());
Upvotes: 11
Reputation: 1227
$options will be used in more views? if the answer is yes, i would put it on the main controller (the one all your controllers extends) or in the main.php.
If that variable will be used just in one view and regards to clases, ids, the place should be in the same view
Upvotes: 0
Reputation: 1384
You should pass your variables from your controller to your view. The data in your variable should come from a model.
Upvotes: 1