0
votes

This is posts/index.php =>

<?php foreach ($allposts as $post) {
            echo '<tr class="class_row">';
            echo '<td>';

            echo $this->Html->link($post['Post']['title'],
                                array('controller'=>'posts','action'=>'view',$post['Post']['id']),
                                array('id'=>'id_anchor_title','class'=>'class_anchor_title') );
            echo '<tr>';
            echo '<td>';
}
?>

I want to call this posts/index.ctp from products/index.ctp => It will be a generic/common index.ctp for all controller. How can i do this ?

In posts/index.ctp the $allposts is used. It's set in posts/index action. But when i will call posts/index.ctp from products/index action different variable is set there. Suppose $this->set('allproducts',$allproducts); is set in products/index action. Now how can i use that allproducts variable in posts/index.ctp ?

3

3 Answers

1
votes

We can use $this->render('view_name'); to use the another view for some other action. I'm not sure how exactly you're going to achieve your goal.

1
votes

As @Vins stated, you can use $this->render('view_name'); at the end of your controller action to render a different view (In your case it should be $this->render('/posts/index');)

In terms of using the variable you want, there are a couple things you can do. One would be to change your set function in each controller to use a common name. For example the posts controller could have $this->set('results',$allposts); and the products controller could have $this->set('results',$allproducts); Doing this, you can always reference $results in your view file. You might also want to set another variable, $pageModel. $this->set('pageModel','Product'); in your products controller for example. Then your posts/index.php file could do something like this:

<?php foreach ($results as $result) {
            echo '<tr class="class_row">';
            echo '<td>';

            echo $this->Html->link($result[$pageModel]['title'],
                                array('controller'=>$this->controller,'action'=>'view',$result[$pageModel]['id']),
                                array('id'=>'id_anchor_title','class'=>'class_anchor_title') );
            echo '<tr>';
            echo '<td>';
}
?>

notice that I replaced 'controller' => 'posts' with 'controller' => $this->controller This will make your view dynamic so the links will always point to the view action of the correct controller.

I hope this helps!

0
votes

if you want to render posts/index.ctp instead of products/index.ctp, use $this->render('/posts/index');

Or you may want to put that in an element (that's the same idea of generic/common index.ctp).