10.1.11 Deleting Posts

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

function delete($id) {
	$this->Post->del($id);
	$this->flash('The post with id: '.$id.' has been deleted.', '/posts');
}
  1. function delete($id) {
  2. $this->Post->del($id);
  3. $this->flash('The post with id: '.$id.' has been deleted.', '/posts');
  4. }

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 with links that allow users to delete posts, however:

/app/views/posts/index.ctp

<h1>Blog posts</h1>
<p><?php echo $html->link('Add Post', '/posts/add'); ?></p>
<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 $html->link($post['Post']['title'], '/posts/view/'.$post['Post']['id']);?>
		</td>
		<td>
		<?php echo $html->link('Delete', "/posts/delete/{$post['Post']['id']}", null, 'Are you sure?' )?>
		</td>
		<td><?php echo $post['Post']['created']; ?></td>
	</tr>
	<?php endforeach; ?>

</table>
  1. /app/views/posts/index.ctp
  2. <h1>Blog posts</h1>
  3. <p><?php echo $html->link('Add Post', '/posts/add'); ?></p>
  4. <table>
  5. <tr>
  6. <th>Id</th>
  7. <th>Title</th>
  8. <th>Actions</th>
  9. <th>Created</th>
  10. </tr>
  11. <!-- Here's where we loop through our $posts array, printing out post info -->
  12. <?php foreach ($posts as $post): ?>
  13. <tr>
  14. <td><?php echo $post['Post']['id']; ?></td>
  15. <td>
  16. <?php echo $html->link($post['Post']['title'], '/posts/view/'.$post['Post']['id']);?>
  17. </td>
  18. <td>
  19. <?php echo $html->link('Delete', "/posts/delete/{$post['Post']['id']}", null, 'Are you sure?' )?>
  20. </td>
  21. <td><?php echo $post['Post']['created']; ?></td>
  22. </tr>
  23. <?php endforeach; ?>
  24.  
  25. </table>

This view code also uses the HtmlHelper to prompt the user with a JavaScript confirmation dialog before they attempt to delete a post.