Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

271
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda