Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
CakePHP 2 Application Cookbook

You're reading from  CakePHP 2 Application Cookbook

Product type Book
Published in Aug 2014
Publisher
ISBN-13 9781782160083
Pages 346 pages
Edition 1st Edition
Languages
Toc

Table of Contents (20) Chapters close

CakePHP 2 Application Cookbook
Credits
Foreword
About the Authors
About the Reviewer
www.PacktPub.com
Preface
1. Lightning Introduction 2. Advanced Routing 3. HTTP Negotiation 4. API Strategies 5. Using Authentication 6. Model Layer 7. Search and Pagination 8. Events System 9. Creating Shells 10. View Templates 11. Unit Tests 12. Migrations Index

Deleting records


Just as we can list and view records, as well as edit and create new ones, you'll also want to be familiar with how to delete records using CakePHP.

In this recipe, we'll create an action that allows us to delete records from our table.

Getting ready

As with the previous recipe, we'll continue using the products table and also extend the ProductsController that we created.

How to do it...

Perform the following steps:

  1. Add the following delete() method to the ProductsController class:

    public function delete($id) {
      if (!$this->request->is('post')) {
        throw new MethodNotAllowedException();
      }
      if ($this->Product->delete($id)) {
        $this->Session->setFlash(__('Product removed: %s', $id));
        return $this->redirect(array('action' => 'index'));
      }
      $this->Session->setFlash(__('Could not remove product'));
      return $this->redirect($this->referer());
    }
  2. Change the content of the index.ctp file to the following:

    <h2><?php echo __('Products'); ?></h2>
    <div>
      <?php echo $this->Html->link(__('Add new product'), array('action' => 'add')); ?>
    </div>
    <table>
      <tr>
        <th><?php echo $this->Paginator->sort('id'); ?></th>
        <th><?php echo $this->Paginator->sort('name'); ?></th>
        <th><?php echo $this->Paginator->sort('created'); ?></th>
        <th><?php echo __('Actions'); ?></th>
      </tr>
      <?php foreach ($products as $product): ?>
        <tr>
          <td><?php echo $product['Product']['id']; ?></td>
          <td><?php echo $this->Html->link($product['Product']['name'], array('action' => 'view', $product['Product']['id'])); ?></td>
          <td><?php echo $this->Time->nice($product['Product']['created']); ?></td>
          <td>
            <?php
            echo $this->Html->link(__('Edit'), array('action' => 'edit', $product['Product']['id']));
            echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $product['Product']['id']), array('confirm' => 'Delete this product?'));
            ?>
          </td>
        </tr>
      <?php endforeach; ?>
    </table>
    <div>
      <?php echo $this->Paginator->counter(array('format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}'))); ?>
    </div>
    <div>
      <?php
      echo $this->Paginator->prev(__('< previous'), array(), null, array('class' => 'prev disabled'));
      echo $this->Paginator->numbers(array('separator' => ''));
    echo $this->Paginator->next(__('next >'), array(), null, array('class' => 'next disabled'));
      ?>
    </div>

How it works...

In this recipe, we added a delete() method to our ProductsController class. This first checks whether the HTTP method used to call the action was POST. In the event it wasn't, we throw a MethodNotAllowedException exception, which is presented as an error page when it is thrown from an action. This is to protect our application against attempts to delete data via a simple URL. If the HTTP method is correct, we proceed to call the delete() method on the Product model, passing to it the ID of the record to delete. If it is successful, we call the setFlash() method on our Session component with a message confirming the removal or with a failure message if the delete() method fails. Finally, we redirect the request to the index() action if the record was deleted successfully—if not, then we are redirecting the user back to the URL where the delete() method was called from. It may also be worth mentioning that the delete() action itself doesn't have a view associated with it, as nothing is displayed to the user as part of the request.

We then returned to the index.ctp view to add an option to delete a product using the postLink() method of the Form helper. This creates a form with a link that allows us to use POST when clicking on the link which submits the form. You will notice that this takes a third argument, which is an array with a confirm key. This prompts the user to confirm the action before submitting the request to delete the record. This is always recommended when dealing with actions that delete records, in case of a mistake on the user's behalf.

See also

  • More details on deleting data in your Models can be found at http://book.cakephp.org/2.0/en/models/deleting-data.html

  • The Adding and editing records recipe

You have been reading a chapter from
CakePHP 2 Application Cookbook
Published in: Aug 2014 Publisher: ISBN-13: 9781782160083
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}