10.1.11 Deleting Posts

ada perubahan tertangguh untuk seksyen ini. More information about translations

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

function delete($id) {
	$this->Post->delete($id);
	$this->Session->setFlash('The post with id: '.$id.' has been deleted.');
	$this->redirect(array('action'=>'index'));
}
  1. function delete($id) {
  2. $this->Post->delete($id);
  3. $this->Session->setFlash('The post with id: '.$id.' has been deleted.');
  4. $this->redirect(array('action'=>'index'));
  5. }

This logic deletes the post specified by $id, and uses $this->Session->setFlash() to show the user a confirmation message after 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', array('action' => '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'], array('action' => 'view', 'id' => $post['Post']['id']));?>
		</td>
		<td>
		<?php echo $html->link('Delete', array('action' => 'delete', 'id' => $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', array('action' => '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'], array('action' => 'view', 'id' => $post['Post']['id']));?>
  17. </td>
  18. <td>
  19. <?php echo $html->link('Delete', array('action' => 'delete', 'id' => $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.