Basic CRUD

Let's start by writing the easiest method, a method to delete a person from the database. All we need is a simple action in the Person Controller. (Note: The order of the methods in the Person.pm file does not matter. You can add this method before or after sub index{ }):

sub delete : Local {
my ($self, $c, $id) = @_;
my $person = $c->model('AddressDB::People')->
find({id => $id});
$c->stash->{person} = $person;
if($person){
$c->stash->{message} = 'Deleted '. $person->name;
$person->delete;
}
else {
$c->response->status(404);
$c->stash->{error} = "No person $id";
}
$c->forward('list'),
}

This action will create a URL that looks like /person/delete/1, where 1 is the person's ID number in the database. Using that ID number that's passed in the URL, we look for the row in the database with that ID. If we find one, we set the status message to Deleted Person's Name and then delete the person (the delete method will also remove any addresses that were associated with that person). If there's no person in the database matching that ID, we set an error message instead. As a good practice, we also set the status of the response in such a case as 404.

Regardless of the outcome, we go back to the list page we came from. There, the new data will show up, with an appropriate message at the top of the screen. This makes it very easy for the user to be sure that his/her action took effect—there's a message saying that it did and the user can look at the list of people and confirm that the person deleted is gone—and it makes it easy to perform another operation, as he/she doesn't have to navigate anywhere. The only disadvantage is that the URL in the URL bar is no longer correct. For now, we'll live with this, but in the next chapter, we'll see how to keep the URL correct and forward the user around in the same way.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.134.133