Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

272
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda