Data Always There
Need data to be available at all times and on all pages? Make use of the beforeRender
controller callback to include common data. If you need it in all pages in your application, add it to /app/app_controller.php. If you just need it for all pages within a specific controller then you can add it to the callbacks on that specific controller.
The beforeRender
callback is called after your controller is called but before your view is rendered. This is handy because you have access to anything you might have set during the exection of your controller.
function beforeRender()
{
$this->set('navdata', $this->MyComponent->getNav($this->sectionId));
}
function myaction()
{
$this->sectionId = 5;
}
In this example, I'm setting a navdata parameter that will be available in my view. The data is coming from a method call on a component.
One of the other things I've been doing is just storing most of my data in $this->data
. The beforeRender
call has access to this and I can either filter or add or use any of the data in that array.
function beforeRender()
{
$this->data = array_merge_recursive($this->data,
$this->MyComponent->getNav($this->data['Project']['id']));
}
I hope that last example made sense. I took the project id that I knew would be in the data set, passed that to my component which returns a multidimensional array and then merges that back into the main data array, all of which will now be available in the view.
Conversation
Hi snook,
I am trying to do something similar..I have left column which displays all the tags or articles that a user has in his library. I am trying to use your idea ..but not sure what do you mean by MyComponent...Can I do the same to call a method of a controller....I tried requestAction but that's not working...and it is also slow in response..so I am planning to directly call contrlloer..is that possible.. please let me known..regards
Ritesh
The beforeRender is within the controller so you can access it using $this. If you want it to call only within a specific controller, then use the beforeRender within a single controller and not within the app_controller.