views:

110

answers:

4

I have an element for my side bar navigation being called from my layouts/default.ctp file, I need to access some data about categories from my Photos controller. How would I go about doing this?

A: 

You can just regard your layous/default.ctp as a normal template,and put

<?php echo $this->element('your element'); ?>

where you need it.

b.t.w,use:

$data = $this->requestAction('controller/action');

to access the data

SpawnCxy
Sorry, maybe I should clarify. I am using <?php echo $this->element('side_nav'); ?> in my layouts/default.ctp I need to get that element, in 'elements/side_nav.ctp' to access data retrieved from the Photos controller.
trobrock
@trobrock,have you tried to use : "$data = $this->requestAction('photos/someaction');"to get data in the element?
SpawnCxy
I have not, I will try that. And sorry I mis-read your answer
trobrock
A: 

Why wouldn't you just do it the standard Cake convention for this?

In the controller,

$this->set( 'categories', $this->Photos->find(...) );

Travis Leleu
A: 

Be careful with requestAction unless you make effective use of caching it can really slow down your application as it starts a whole new request cycle every time you call it.

Travis Leleu's answer would be the standard way of doing things. But, if you must import the data (for portability or whatever reason) into the element then requestAction is not the way to go.

As you are not performing any business logic that must be in the controller I strongly recommend you import and instantiate the model class as a singleton into your element. You can do this using ClassRegistry::init();

$Photo = ClassRegistry::init('Photo');
$Photo->find('all');

If you need to do any additional processing of the data you should do that in the model itself either using Cakes afterFind callback or making a custom method in your Photo model:

class Photo extends AppModel {

    function customFind () {
        $photos = $this->find('all');
        foreach ($photos as $photo) {
            //processing code here...
        }
    }

}

Then call it in your element:

$Photo = ClassRegistry::init('Photo');
$Photo->customFind();

Basically what I'm trying to get across here is the only situation where requestAction is appropriate is where you need to do things like redirects or using components.

If you a simply retrieving and/or manipulating data then it belongs in the model.

rich97
A: 

You can send data to your element. For example in your default.ctp:

<?php echo $this->element('side_nav', $your_data); ?>

and in your side_nav.ctp you can process that data.

Jamal Aziz