Search code examples
variablescakephpviewcakephp-3.0

CakePHP 3.7 - Access view variable from controller


Inside AppController->beforeRender() I would to check whether a view variable is already set and see its value.

How can you access view variables from a controller in CakePHP 3.7?

This used to be possible with $this->viewVars['variable_name'], but it has been deprecated.

I tried $this->viewBuilder()->getVars() but that returns an empty array, while there certainly are view variables.


Solution

  • Summarising an answer from the comments: this is not directly possible.
    Accessing the variables through the viewBuilder() won't work because it only receives the viewvars as the view is being built.

    A custom element encapsulating the variables to be accessed could be a solution.

    I ended by setting some variables as default: in AppController->initialize() the view variable status is set as "OK", other controllers and methods can then simply override it.