Tuesday, January 18, 2022

[FIXED] How to Pass the Controller Data to JS File in CakePHP 3.0

Issue

In CakePHP 2.0, I've used the link below to pass controller data to a js file. However, I can longer use this method anymore as CakePHP 3.0 has removed js helper.

Is there a new technique for me to pass the controller data to a js file or alternative method beside using js helper with the link below?

http://www.php-dev-zone.com/2014/01/how-to-pass-controller-data-to-js-file.html

Relevant code:

public function beforeRender()
{
    // We are Setting the jsvariables array which holds the
    // variables that will be used in js files.
    $this->set('jsVars', $this->_jsvariables);
}
<?php echo $this->Html->scriptBlock('var jsVars = '.$this->Js->object($jsVars).';'); ?>

Solution

Just check what the JsHelper::object() method was doing, and then do it manually.

https://github.com/cakephp/.../2.7.0/lib/Cake/View/Helper/JsBaseEngineHelper.php#L127

It's basically just a call to json_encode(), so simply replace the helper method call accordingly:

<?php echo $this->Html->scriptBlock('var jsVars = ' . json_encode($jsVars) . ';'); ?>


Answered By - ndm

No comments:

Post a Comment

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