PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, March 19, 2022

[FIXED] Yii1: Controller::beforeRender in Yii2

 March 19, 2022     php, yii, yii2     No comments   

Issue

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?


Solution

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()


Answered By - Joe Miller
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing