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');
}
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 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> /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>
This view code also uses the HtmlHelper to prompt the user with a JavaScript confirmation dialog before they attempt to delete a post.
See comments for this section
