0

What's the best way to get data from various models within my layout file(main.php to use in footer). For example, I want my footer to always contain 5 records from my products model/table.

So I have two questions:

  1. How can I display data within a layout/common component file?
  2. When only wanting five records would this be done within a model function or in my view foreach loop?
Jason
  • 15,017
  • 23
  • 85
  • 116
con322
  • 1,119
  • 7
  • 16
  • 29

4 Answers4

0

In order to display data within a layout file, you must have a variable in the Controller scope. So if you have something like:

class BookController extends Controller {
   /*
    * The var below will be accessible from your template files (main.php, etc)
    * and any other view file
    */
    public $globalContent = 'Hello';

    public function actionIndex(){
         //The var below is not accessible in your main.php
         $localContent = 'World'; 
         $this->render('index', array('localContent' => $localContent));
    }
}

A good way to have a common variable among all controllers is to have your controllers extend a custom Controller.php.

Refer to How do I pass a global variable in Main layout page before $content in Yii2 for more information

Community
  • 1
  • 1
Davi Bandeira
  • 116
  • 1
  • 6
0

You can also use this in your layout file, but I think it is not a good way, database transactions should be in Model.

$command = Yii::$app->db->createCommand("select * from product;");
$products = $command->queryOne();
ankitr
  • 5,992
  • 7
  • 47
  • 66
0

I have done the following which works.

Created a controller with my common/components folder with the following code within it:

<?php

namespace common\components;

use frontend\models\ProductItem;

class FooterComponent
{
    public static function getProducts()
    {
        return ProductItem::find()->limit(8)->all();
    }
}

And then within my layout file (main.php)

<?php 

foreach(common\components\FooterComponent::getProducts() as $product){
      echo "<li><a href='" . $product->id . "'>" . $product->name . "</a></li>";
  } 

?>
con322
  • 1,119
  • 7
  • 16
  • 29
0

I solve the problem in a similar way. Following this tutorial http://www.bsourcecode.com/yiiframework2/how-to-create-custom-widget-in-yii2-0-framework/ I created a widget in $app/components directory and use its returned value to show it in default layout.

arogachev
  • 33,150
  • 7
  • 114
  • 117
Rsnail
  • 1
  • It would be helpful to quote relevant text from the linked article inline so that it becomes part of your answer and this site. If the link becomes broken in the future, and you quoted the text inline, someone would still have a chance at following your advice. – user700390 Apr 17 '15 at 11:58