Search code examples
cakephpposts

How to add posts to homepage cakephp?


I'm new to cakephp. So I want to ask you, how to add posts to homepage. I created posts by this tutorial http://book.cakephp.org/2.0/en/getting-started.html#blog-tutorial

What should I do next?

I tried to google it, but nothing works.

Thanks.

home.ctp

<h1>Blog posts</h1>
<table>
    <tr>
        <th>Id</th>
        <th>Title</th>
        <th>Created</th>
    </tr>

    <!-- Here is 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'],
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>
        </td>
        <td><?php echo $post['Post']['created']; ?></td>
    </tr>
    <?php endforeach; ?>
    <?php unset($post); ?>
</table>

Solution

  • You have to redirect your homepage to the index() of PostsController.

    Go to your routes.php file and change this line:

    Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
    

    for this one:

    Router::connect('/', array('controller' => 'posts', 'action' => 'index'));
    

    (assuming that your index() actually contain a list of all your posts)

    Router::connect will catch when an user attempt to go to the url on the first parameter, and will redirect it to the action in the controller on the second parameter