Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
Yii1: Controller::beforeRender in 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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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()
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!