RSS

Search Engine

Saturday, May 15, 2010

Deleting Posts

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

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:
Plain Text View



Blog posts


link('Add Post', array('action' => 'add')); ?>





















Id Title Actions Created

link($post['Post']['title'], array('action' => 'view', 'id' => $post['Post']['id']));?>

link('Delete', array('action' => 'delete', 'id' => $post['Post']['id']), null, 'Are you sure?' )?>


1.
2.

Blog posts


3.

link('Add Post', array('action' => 'add')); ?>


4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
18.
21.
22.
23.
24.
25.
IdTitleActionsCreated

16. link($post['Post']['title'], array('action' => 'view', 'id' => $post['Post']['id']));?>
17.

19. link('Delete', array('action' => 'delete', 'id' => $post['Post']['id']), null, 'Are you sure?' )?>
20.


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

0 comments:

Post a Comment