cakephp

Page 129

The Cake Blog Tutorial

Now that you have your validation in place, use the app to try to add a post without a title or body to see how it works.

A.11. Deleting Posts Next, let's make a way for users to delete posts. Start with a delete() action in the PostsController:

Example A.10. /app/controllers/posts_controller.php (delete action only) function delete($id) { $this->Post->del($id); $this->flash('The post with id: '.$id.' has been deleted.', '/posts'); }

This logic deletes the post specified by $id, and uses flash() to show the user a confirmation message before redirecting them on to /posts. Because we're just executing some logic and redirecting, this action has no view. You might want to update your index view to allow users to delete posts, however.

Example A.11. /app/views/posts/index.thtml (add and delete links added) <h1>Blog posts</h1> <p><?php echo $html->link('Add Post', '/posts/add'); ?></p> <table> <tr> <th>Id</th> <th>Title</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 $html->link($post['Post']['title'], '/posts/view/'.$post['Post']['id']);?> <?php echo $html->link( 'Delete', "/posts/delete/{$post['Post']['id']}", null, 'Are you sure?' )?> </td> </td> <td><?php echo $post['Post']['created']; ?></td> </tr> <?php endforeach; ?> </table> 119


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.