Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

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

In the controller,

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top