简体   繁体   中英

Should i calling model direct from view yii2

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

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']
) ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM