0
votes

Right, i have:

Controller/PostsController.php
Model/Post.php
View/Posts/index.ctp

the controller finds all the posts in a database and then passes the values into my view/Posts/index.ctp, where i foreach though each post.

I now want to be able to access the same posts but on another controller and view. How do i do this?

PostsController is;

class PostsController extends AppController {


    public function index() {
        $this->set('posts', $this->Post->find('all'));

    }

 }

View/Posts/index.ctp is;

 <table>
        <tr>
            <th>Id</th>
            <th>Title</th>
            <th>Actions</th>
            <th>Created</th>
        </tr>

    <!-- Here's where we loop through our $posts array, printing out post info -->

        <?php foreach ($posts as $post): ?>
        <tr>
            <td><?php echo $post['Post']['id']; ?></td>
            <td>
                <?php
                    echo $this->Html->link(
                        $post['Post']['title']
                    );
                ?>
            </td>


            <td>
                <?php echo $post['Post']['created']; ?>
            </td>
        </tr>
        <?php endforeach; ?>

    </table>

Now in my AboutsController and Abouts/index.ctp i want to be able to access the same data so that i can show the posts on the view/abouts/index.ctp

when i make the view/abouts/index.ctp, have the same code as View/Posts/index.ctp i get the error message;

Undefined variable: posts [APP\View\Abouts\index.ctp, line 12]

This is because i do not know how to make the data accessible in my Abouts/Controller.

1

1 Answers

1
votes

For the global variable , i suggest to set it un the appController from which you can access into it wherever you are, in the appController :

class AppController extends Controller {
    var $uses = array('Post'); // to use the model 
      public function beforeFilter(){
         $this->set('posts', $this->Post->find('all'));
      }
}

then you can get posts in any view ...