Passing Data from CakePHP to Helper

I need to exchange data between a component and an assistant. I am converting my homemade payment data form generator into CakePHP plugin, and I would like to be able to fill in payment data from the controller (using the component) and use an auxiliary tool to print the data.

Everything I tried so far felt too hacked, so let me ask you: is there an elegant way to transfer data from a component to an assistant?


edit:

I solved this specific situation by adding the original instance of formadata to ClassRegistry during component initialization. In this way, the helper can also access the instance using ClassRegistry.

However, this only works for objects, so the question remains open.

+4
source share
3 answers

Is there an elegant way to transfer data from a component to an assistant?

Yes, just like you pass data to an assistant. In your opinion.

Inside your component, I would do something like the following. The beforeRender() action is a callback to the CakePHP component .

 public function beforeRender(Controller $controller) { $yourVars = 'some data'; $goHere = 'other stuff'; $controller->set(compact('yourVars', 'goHere')); } 

Then, in your opinion, you can transfer the data to your assistants, as usual.

 // view or layout *.ctp file $this->YourHelper->yourMethod($yourVars); $this->YourHelper->otherMethod($goHere); 
+4
source

Having a similar problem, I found that this solution works best for me.

You can use the helper __construct method paired with the $ controller-> helpers array.

Since Helper::_construct() is called after Component::beforeRender , you can modify the $controller->helpers['YourHelperName'] array to pass data to your helper.

Component Code:

 <?php public function beforeRender($controller){ $controller->helpers['YourHelperName']['data'] = array('A'=>1, 'B'=>2); } ?> 

Assistant Code:

 <?php function __construct($View, $settings){ debug($settings); /* outputs: array( 'data' => array( 'A' => (int) 1, 'B' => (int) 2 ) ) */ } ?> 

I am using CakePHP 2.0, so this solution should be tested for earlier versions.

+6
source

In addition to being @Vanja, you can also do this immediately before creating a new view in your controller:

 // In your controller method // must be set prior to instantiating view $this->helpers['YourHelperName']['paramsOrAnyName'] = ['var' => $passed_var]; $_newView = new View($this); $return_result = $_newView->render($element_to_view, $layout); 
0
source

All Articles