Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii1: Controller::beforeRender in Yii2

Tags:

php

yii

yii2

I'm migrating an old app developed in Yii1 to Yii2.

I used to have a array in the controller that was storing all the variables that I would need to send to the frontend as a JavaScript:

public $jsVars;
public function toJSObject($params){
    $this->jsVars = array_merge($this->jsVars, $params);
}

private function printJSVarsObject(){
  //convert my php array into a js json object
}

When I needed a variable to be exposed in Javascript, I would just use $this->toJSObject, in the View or in the Controller.

Then, in the controller I also used to have:

public function beforeRender($view){
  $this->printJSVarsObject();
}

In Yii2, I had to configure the View component with a custom View and then attach an event:

namespace app\classes;

use yii\base\Event;
use yii\helpers\Json;

Event::on(\yii\web\View::className(), \yii\web\View::EVENT_END_BODY, function($event) {
    $event->sender->registerJSVars();
});

class View extends \yii\web\View {
    public $jsVars = [];

    public function addJsParam($param){
        $this->jsVars = array_merge($this->jsVars, $param);
    }

    public function registerJSVars() {
        $this->registerJs(
            "var AppOptions= " . Json::htmlEncode($this->jsVars) . ";",
            View::POS_END,
            'acn_options'
        );
    }
}

But, having the event outside the class seems weird to me. Also, while I'm in the controller, I won't be able to use my former approach using this method.

Obviously, I'm missing something, or my approach is just incorrect.

How do you guys do that?

like image 248
Chux Avatar asked May 03 '17 10:05

Chux


1 Answers

If you're trying to access properties of the controller from a view (see above comments!), you can use;

$this->context

to return an instance of the currently used controller from within the view file. So to access your beforeRender() method you would just use

$this->context->beforeRender()
like image 136
Joe Miller Avatar answered Oct 15 '22 02:10

Joe Miller