0

i need to send data from controllers to main layout (something like notifier of a new messages in top menu) i need it in all app(global)

i found one way to to pass variables to layout

Yii::$app->controller->myvar

from class property to layout, but i think it's not best way to duplicate code to all controllers, maybe i suppose to extend base Controller and set my logic here?

Tell me please the best practice to do what i want.

ps. Tnx and sorry for my English

user2842
  • 25
  • 6
  • Check this question http://stackoverflow.com/questions/28038912/how-to-pass-param-from-controller-to-layout-in-yii2 – arogachev Feb 03 '15 at 11:18
  • Why you just dont use global app params Yii::$app->params['foo'] = 'bar'; // controller and echo Yii::$app->params['foo']; // in view/layout/elsewhere – ustmaestro Mar 15 '16 at 10:38

3 Answers3

2

In the controller, you can use

$this->view->params['name'] = 123

and in the layout

<?= $this->params['name'] ?>
Cthulhu
  • 1,379
  • 1
  • 13
  • 25
1

1) You can use yii global app params

Yii::$app->params['foo'] = 'bar'; // controller

and

echo Yii::$app->params['foo']; // in view/layout/controllers/elsewhere

2) You can use session. Create a controller, that will be extended by others, with these 3 functions:

<?php
namespace common\components;
use Yii;
use yii\web\Controller;

class BaseController extends Controller
{

    /**
     * Set user flash notice
     * @param $message
     * @return mixed
     */
    public function setFlash($key, $message){
        return Yii::$app->session->setFlash($key, $message);
    }

    /**
     * Has user flash notice
     * @param $message
     * @return mixed
     */
    public function hasFlash($key){
        if(Yii::$app->session->hasFlash($key)) return True;
        else return false;
    }

    /**
     * Get user flash notice
     * @param $message
     * @return mixed
     */
    public function getFlash($key){
        return Yii::$app->session->getFlash($key);
    }
}

now in your controllers

use common\components\BaseController;
...
class MyController extends BaseController
...
$this->setFlash('foo','bar'); // setting flash var

and in your views

echo $this->context->getFlash('foo'); // getting flash var

or

echo Yii::$app->controller->getFlash('foo'); // getting flash var
ustmaestro
  • 1,233
  • 12
  • 20
0

The below line add in config\main.php

'user'=>array( 'class'=>'WebUser', // enable cookie-based authentication 'allowAutoLogin'=>true, ),

After that create new file in protected\components\WebUser.php, In this WebUser.php file

class WebUser extends CWebUser { private $_model;

function Update()
{
    return $this->myvar='this is my variable';
}

}

You can access in layout file like this echo Yii::app()->user->update();

sv.sasi
  • 7
  • 4