codeofaninja
website

CakePHP 2.x CRUD Tutorial

Photo of Mike Dalisay
Modified Sunday, April 1, 2012
by - @ninjazhai
*This post is just meant to be an example, not production-ready code.

Hi guys, today I just want to update my CakePHP Crud Tutorial from 1.3.x to 2.x. Using CakePHP 2.x can give us lots of benefits such as improved support for PostgreSql, SQLite and SqlServer, HTML 5 form inputs support in form helper, a sexier default look taking advantage of new CSS 3 features, a lot faster, almost everything is now lazy-loaded, and even on debug mode you will feel your applications flying, more here, here and here.

CakePHP 2.x CRUD Tutorial
Click to enlarge

You can download the code here:


Table used:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `email` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ;

The default layout was used in this tutorial. It was found in app/View/Layouts/default.ctp

Create Record

Controller: app/Controller/UsersController.php

public function add(){

    //check if it is a post request
    //this way, we won't have to do if(!empty($this->request->data))
    if ($this->request->is('post')){
        //save new user
        if ($this->User->save($this->request->data)){
       
            //set flash to user screen
            $this->Session->setFlash('User was added.');
            //redirect to user list
            $this->redirect(array('action' => 'index'));
           
        }else{
            //if save failed
            $this->Session->setFlash('Unable to add user. Please, try again.');
           
        }
    }
}

View: app/View/Users/add.ctp

<h2>Add New User</h2>

<!-- link to add new users page -->
<div class='upper-right-opt'>
    <?php echo $this->Html->link( 'List Users', array( 'action' => 'index' ) ); ?>
</div>

<?php
//this is our add form, name the fields same as database column names
echo $this->Form->create('User');

    echo $this->Form->input('firstname');
    echo $this->Form->input('lastname');
    echo $this->Form->input('email');
    echo $this->Form->input('username');
    echo $this->Form->input('password', array('type'=>'password'));
   
echo $this->Form->end('Submit');
?>

Read Records

Controller: app/Controller/UsersController.php

public function index() {
    //to retrieve all users, need just one line
    $this->set('users', $this->User->find('all'));
}

View: app/View/Users/index.ctp

<h2>Users</h2>

<!-- link to add new users page -->
<div class='upper-right-opt'>
    <?php echo $this->Html->link( '+ New User', array( 'action' => 'add' ) ); ?>
</div>

<table style='padding:5px;'>
    <!-- table heading -->
    <tr style='background-color:#fff;'>
        <th>ID</th>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Username</th>
        <th>Email</th>
        <th>Actions</th>
    </tr>
   
<?php

   
    //loop to show all retrieved records
    foreach( $users as $user ){
   
        echo "<tr>";
            echo "<td>{$user['User']['id']}</td>";
            echo "<td>{$user['User']['firstname']}</td>";
            echo "<td>{$user['User']['lastname']}</td>";
            echo "<td>{$user['User']['username']}</td>";
            echo "<td>{$user['User']['email']}</td>";
           
            //here are the links to edit and delete actions
            echo "<td class='actions'>";
                echo $this->Html->link( 'Edit', array('action' => 'edit', $user['User']['id']) );
               
                //in cakephp 2.0, we won't use get request for deleting records
                //we use post request (for security purposes)
                echo $this->Form->postLink( 'Delete', array(
                        'action' => 'delete',
                        $user['User']['id']), array(
                            'confirm'=>'Are you sure you want to delete that user?' ) );
            echo "</td>";
        echo "</tr>";
    }
?>
   
</table>

Update Record

Controller: app/Controller/UsersController.php

public function edit() {
    //get the id of the user to be edited
    $id = $this->request->params['pass'][0];
   
    //set the user id
    $this->User->id = $id;
   
    //check if a user with this id really exists
    if( $this->User->exists() ){
   
        if( $this->request->is( 'post' ) || $this->request->is( 'put' ) ){
            //save user
            if( $this->User->save( $this->request->data ) ){
           
                //set to user's screen
                $this->Session->setFlash('User was edited.');
               
                //redirect to user's list
                $this->redirect(array('action' => 'index'));
               
            }else{
                $this->Session->setFlash('Unable to edit user. Please, try again.');
            }
           
        }else{
       
            //we will read the user data
            //so it will fill up our html form automatically
            $this->request->data = $this->User->read();
        }
       
    }else{
        //if not found, we will tell the user that user does not exist
        $this->Session->setFlash('The user you are trying to edit does not exist.');
        $this->redirect(array('action' => 'index'));
           
        //or, since it we are using php5, we can throw an exception
        //it looks like this
        //throw new NotFoundException('The user you are trying to edit does not exist.');
    }
   

}

View: app/View/Users/edit.ctp

<h2>Edit User</h2>

<!-- link to add new users page -->
<div class='upper-right-opt'>
    <?php echo $this->Html->link( 'List Users', array( 'action' => 'index' ) ); ?>
</div>

<?php
//this is our edit form, name the fields same as database column names
echo $this->Form->create('User');

    echo $this->Form->input('firstname');
    echo $this->Form->input('lastname');
    echo $this->Form->input('email');
    echo $this->Form->input('username');
    echo $this->Form->input('password', array('type'=>'password'));
   
echo $this->Form->end('Submit');
?>

Delete Record

We won't have view for delete because this is triggered only when the user clicked the delete option on the index page and clicked ok on the pop up.

Controller: app/Controller/UsersController.php

public function delete() {
    $id = $this->request->params['pass'][0];
   
    //the request must be a post request
    //that's why we use postLink method on our view for deleting user
    if( $this->request->is('get') ){
   
        $this->Session->setFlash('Delete method is not allowed.');
        $this->redirect(array('action' => 'index'));
       
        //since we are using php5, we can also throw an exception like:
        //throw new MethodNotAllowedException();
    }else{
   
        if( !$id ) {
            $this->Session->setFlash('Invalid id for user');
            $this->redirect(array('action'=>'index'));
           
        }else{
            //delete user
            if( $this->User->delete( $id ) ){
                //set to screen
                $this->Session->setFlash('User was deleted.');
                //redirect to users's list
                $this->redirect(array('action'=>'index'));
               
            }else{ 
                //if unable to delete
                $this->Session->setFlash('Unable to delete user.');
                $this->redirect(array('action' => 'index'));
            }
        }
    }
}

For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
 
 
Fundamentals
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.