0
votes

I'm new to MVC and Yii Framework. The $model variable seems very confusing to me.

Where is it declared in the fist place? Where does it come from?

When I work with GridView I see that some functions take $model as a parameter. Neither model nor model search of this GridView declares $model variable anywhere. Yet it is widely used in all sorts of data management. It just doesn't make sense to me.

So I need a simple, straight forward, "for dummies" explanation of $model variable in Yii Framework v2. Help in clarifying these questions is much appreciated: 1. What is the origin of $model variable? 2. How to identify what model of the app is the $model variable representing when it's used in view files? 3. There are sometimes multiple $model variables in a single view file. Do all of them represent one model class? How to distinguish them when used for multiple classes?

Thanks.

2

2 Answers

2
votes

If you are unsure where $model, $searchModel and other variables come from, you are most likely searching for them on the view file where they are used.

They are created on the controller that renders said view, just like any other object/variable.

From the controller, you can render a view and pass objects/variables the following way:

// MyController.php
...
public function actionMyAction($id) {
    // Create and manipulate $model and $searchModel
    ...
    /*
     * First param is the name of the view to be rendered
     * Second param is an Associative Array with params
     * that will be made available to the view.
     */
    return $this->render('my-view-name', [
        'model' => $model,
        'searchModel' => $searchModel,
    ]);
}
1
votes

The $model is a var as the others ...normally in the yii2 samples contain an instance of a model class (as tiplically an active record=)

assuming you have a class

 class Category extends \yii\db\ActiveRecord
 {
  ........

a tipical code could be

 $model = Category::findOne($id);

where Category::findOne($id) find an instance form database using $id as primary key and assign the result to $model ..

then you can access to the instance attribute (eg:attribute1) using

$model->attribute1

you can take a look at this guide

http://www.yiiframework.com/doc-2.0/guide-index.html http://www.yiiframework.com/doc-2.0/guide-structure-models.html http://www.yiiframework.com/doc-2.0/guide-db-active-record.html