Reputation: 155
I'm little confused cuz, here in view they do direct call to model thus not passing it through the controller. http://www.yiiframework.com/doc-2.0/guide-input-forms.html Scroll to the bottom of the page...
echo $form->field($model, 'product_category')->dropdownList(
ProductCategory::find()->select(['category_name', 'id'])->indexBy('id')->column(),
['prompt'=>'Select Category']
);
And the guide from here http://www.yiiframework.com/doc-2.0/guide-structure-views.html at the bottom again there is a Best Prictice section and one of the topic is: (views) should not contain code that performs DB queries. Such code should be done in models.
Thanks
Upvotes: 3
Views: 670
Reputation: 4076
I agree with you about the understanding of the "Best Practices". I think we should avoid calling methods that perform db queries inside the views. Plus, all queries are already in the model. So does not make sense to me to have external queries outside there.
I worked with some projects using Yii2 framework (not created by me) and i just made a quick search here. The only case i had of something similar to this, was exactly when we have a form or gridview and tries to show all occurrences of another model.
In that scenario I prefer to create a function in my model just to handle this. Something like:
MODEL
/**
* @return array
*/
public function getAllAnotherModel()
{
return AnotherModel::find()->all();
}
VIEW:
<?= $form->field($model, "id_another_model")->dropDownList(
ArrayHelper::map($model->allAnotherModel, 'id', 'name'),
['prompt' => 'Select']
) ?>
Upvotes: 2