I just started to learn Yii2 and immediately ran into a misunderstanding of how to display the result of a query to the database in view. I created a post table and try to pull a dataset out of it. It seems everything is logical but does not work.
Model: localhost \ yii2-basic \ models \ Post.php

namespace app\models; use yii\db\ActiveRecord; class Post extends ActiveRecord { public static function tableName() { return 'post'; } } 

Controller: localhost \ yii2-basic \ controllers \ PostController.php

 namespace app\controllers; use yii\web\Controller; use app\models\Post; class PostController extends Controller { public function actionIndex(){ $posts = Post::find()->all(); return $this->render('index', compact('posts')); } } 

View: localhost \ yii2-basic \ views \ post \ index.php

 var_dump($posts); 

When trying to output, phpstorm already tells you that this $posts variable is not declared and underlines it. Why it happens? It seems that the controller should render it in a view, but this does not happen. Tell me why this is happening?

  • one
    return $ this-> render ('index', ['posts' => $ posts])? - Serik Shaikamalov
  • one
    I would not recommend using compact. In general, all of these functions that take / give away variables from the context should be deleted long ago or at least zadepekitit - they are evil and govnokod. - PECHAIRTER

1 answer 1

The storm emphasizes the variable in the view because it does not know which variables are passed to the view. To prompt the storm, you can add a comment at the very beginning of the file.

 /** * @var $this yii\web\View * @var $posts array */ 

Now, if we use other views in the current view, the storm will know that $ this is a View object and will display hints. Also, it will not “swear” on the $ posts variable.

To find out why the view does not display anything, you need to check in the controller what comes into the variable.

 namespace app\controllers; use yii\web\Controller; use app\models\Post; class PostController extends Controller { public function actionIndex(){ $posts = Post::find()->all(); var_dump($posts); // смотрим, что в переменной до вьюхи. return $this->render('index', compact('posts')); } }