A
A
AlikDex2016-07-15 19:55:43
Yii
AlikDex, 2016-07-15 19:55:43

global variable in yii2?

In general, look. There is a layout, like main. Standard like this. With a category column. These categories are displayed by the widget. Multilevel. Each category has a list of products. The point is. We go to the site, and get a list of some goods, they do not suit, of course, we go to the category to look for the right one. Here. At this time, the processing of category jumps is handled by the CategoryController.php controller, for example. There is also a rule for routing:
'<category:\w+>' => 'category/index',
So, we entered some category, the controller was called, the action was called, the incoming parameter, of course, turned out:

public function actionIndex($category = null)
{
    //....
}

At this time, the widget receives its variable obtained from the action parameter:
echo \frontend\widgets\Categories::widget([
    'category' => isset(Yii::$app->controller->actionParams['category']) ? Yii::$app->controller->actionParams['category'] : null,
]);

Everything is fine, great, works!
Let's get to the question. =)
As we remember, we still have products that have their own category! So. We rummaged around, found the product we needed in the iphone category, for example. We went to the page, and here we have a problem. Categories for the widget from the url can no longer be obtained, but it is in the product. How to pass this category to the widget? To show the active category for the product. Head-on solution:
Yii::$app->controller->actionParams['category'] = $model->category->slug;

Those. directly barbarously enter the variable in the action parameters. The second option is to store a global variable somewhere. Sessions are of course possible, but also do not seem to be an option. Any other ideas?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita, 2016-07-15
@AlikDex

In the controller:
$this->view->params
Right in the view:
$this->params
See how standard breadcrumbs work.

M
Michael, 2016-07-15
@springimport

You can make a service that the controller will manage. In the normal case, it will set the parameter with url, in others it will be different.
You can also use session .
PS Or write in English, or don't make mistakes .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question