As a newbie to CakePHP I need tutorials to guide me and teach me how to use it. I stumbled upon Fabio Cevasco’s CakePHP tutorial on SitePoint. This tutorial dates back to 2006. The post doesn’t mention the used CakePHP version. It was not hard to guess that it is outdated for the year of 2009. But that is ok…

Gladly I made it working for 1.2.x.x, so here it is:

An updated version of Fabio’s article “The CakePHP Framework: Your First Bite” on SitePoint. His version was written when CakePHP 1.1.x.x was the real deal. In this article I have modified the code and made it work with CakePHP 1.2.x.x

In this tutorial you will create a straight forward and simple notes application. You will be able to list, add, edit and delete notes using CakePHP 2.1.x.x and MySQL. Furthermore, you’ll validate the form entries of the notes and you’ll be using a different layout for this application.

This post requires basic knowledge of PHP, MySQL. You also need to have a basic understanding of the MVC structure as I won’t go into detail like Fabio does. Here you’ll find the modified code and little bits of extras. You can take a look at the original post for slightly more theory and nifty details of the code used in this application.

Happy coding!

Tutorial’s details

Title: Updated version of The CakePHP Framework: Your First Bite
CakePHP version: 1.2.x.x (download latest version)
Parts: part 1 | (part 2)
Link to this post: http://www.missphp.com/blog/the-cakephp-framework-your-first-bite-version12xx-part-1/

Preparation – Database (original link)

Step 1.1 Make sure you have a database user and password. If not, create!
Step 1.2 Create a database (if you haven’t already) with the name memo
Step 1.3 Create the MySQL table in the ‘memo’ database using this piece of SQL:

1
2
3
4
5
6
7
CREATE TABLE notes (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50),
body TEXT,
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);

If you have a totally fresh install of a CakePHP, chances are that you don’t have a database file configured. Otherwise skip this step and go to Step 1.6:
Step 1.4.1 Go to the folder /app/config/ and
Step 1.4.2 Open the file database.php.default
Step 1.4.3 Save it as database.php

Step 1.5 Edit the database configuration file as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php 
class DATABASE_CONFIG {
   var $default = array(
      'driver' => 'mysql',
      'persistent' => false,
      'host' => 'localhost',
      'login' => 'username_here', // replace 'username_here' with your database username
      'password' => 'password_here', // replace 'password_here' with your database password 
      'database' => 'memo',
      'prefix' => '', // no need to have this for this tutorial
   );
 
   var $test = array(
      'driver' => 'mysql',
      'persistent' => false,
      'host' => 'localhost',
      'login' => 'spacecake',
      'password' => 'extra',
      'database' => 'strong',
      'prefix' => '',
   );
}
?>

Creating the model

Step 1.6.1 Create a file named note.php and save this in the /app/models/ directory.
Step 1.6.2 Add the following code to your Note-model:

1
2
3
4
5
6
<?php 
class Note extends AppModel 
{ 
   public $name = 'Note'; 
} 
?>

Creating the controller

Step 1.7.1 Create a file named notes_controller.php and save this in the /app/controllers/ directory.
Step 1.7.2 Add the following code to your Notes-controller:

1
2
3
4
5
6
<?php 
class NotesController extends AppController 
{ 
	public $name = 'Notes'; 
} 
?>

Creating views & actions for your notes application (original link)

Step 2.1 Create a folder named notes in the /app/views/ directory

The first page of your application

The page where we will list all the notes that are in the database.
Step 2.2 Create a file named index.ctp in the /app/views/notes/ directory.
Step 2.3 Add the following code to your index-view:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<h1>My Notes</h1> 
<p><?php echo $html->link('Add a Note', '/notes/add') ?></p> 
<table> 
   <tr> 
       <th>Id</th> 
       <th>Title</th> 
       <th>Created</th> 
   </tr> 
   <?php foreach ($notes as $note): ?> 
   <tr> 
       <td><?php echo $note['Note']['id']; ?></td> 
       <td> 
     <?php echo $html->link($note['Note']['title'], "/notes/view/{$note['Note']['id']}")?> 
     [<?php echo $html->link('Edit', "/notes/edit/{$note['Note']['id']}")?>, 
     <?php echo $html->link('Delete', "/notes/delete/{$note['Note']['id']}", null, 'Are you sure to delete the following note? \n - '.$note['Note']['title'].'')?>] 
       </td> 
       <td><?php echo $note['Note']['created']; ?></td> 
   </tr> 
   <?php endforeach; ?> 
</table>

Step 2.4 Add the following function to your Notes-controller (in /app/controllers/notes_controller.php)

1
2
3
4
public function index()
{
   $this->set('notes', $this->Note->findAll());
}

Viewing a single note

Step 2.5 Create a file named view.ctp in the /app/views/ directory.
Step 2.6 Add the following code to it:

1
2
3
<h1><?php echo $data['Note']['title']?></h1> 
<p><small>Created: <?php echo $data['Note']['created']?></small></p> 
<p><?php echo $data['Note']['body']?></p>

Step 2.7 Add the corresponding view action to the controller. Add the following function to your Notes-controller (in /app/controllers/notes_controller.php)

1
2
3
4
5
public function view($id)
{
    $this->Note->id = $id;
    $this->set('data', $this->Note->read());
}

Adding, Editing and Deleting Notes

Adding a new note

Step 3.1 Create a file named add.ctp in the /app/views/ directory.
Step 3.2 Add the following code to it:

1
2
3
4
5
6
<h1>Add a note</h1>
<form action="<?php echo $form->url('/notes/add')?>" method="POST">
	<p>Title: <?php echo $form->text('Note.title', array('size' => '40'))?></p>
    <p>Body: <?php echo $form->textarea('Note.body')?></p>
    <p><?php echo $form->submit('Save')?></p>
</form>

Use $form->input instead of $form->text – Some framework magic

Check this out. There are 2 ways to display the input field of a form. Both line of codes have almost the same amount of characters. But the output differs.
Method 1:

<?php echo $form->text('Note.title', array('size' => '40'))?>

Method 1 produces:

<input id="NoteTitle" name="data[Note][title]" size="40" type="text" />

Method 2:

<?php echo $form->input('Note.title', array('size' => '40'))?>

Method 2 produces:

<div class="input text">
   <label for="NoteTitle">Title</label>
   <input id="NoteTitle" maxlength="50" name="data[Note][title]" size="40" type="text" />
</div>

A div and label are automatically added to your field. Instead of having to hand code this all, you can manage to get this result with just 1 character more.
Which one to choose? It depends on your preferences as both work.

Step 3.3 Add the following function to your Notes-controller (in /app/controllers/notes_controller.php)

1
2
3
4
5
6
7
8
9
10
public function add()
{
	if (!empty($this->data['Note']))
	{
		if($this->Note->save($this->data['Note']))
		{
			$this->flash('Your note has been updated.','/notes/');
		}
	}
}

Editing an existing note

Step 3.4 Create a file named edit.ctp in the /app/views/ directory.
Step 3.5 Add the following code to it:

1
2
3
4
5
6
7
<h1>Edit Note</h1> 
<form action="<?php echo $form->url('/notes/edit')?>" method="post"> 
   <?php echo $form->hidden('Note.id'); ?> 
   <p>Title: <?php echo $form->text('Note.title', array('size' => '40'))?></p> 
   <p>Body: <?php echo $form->textarea('Note.body')?></p> 
   <p><?php echo $form->submit('Save') ?> </p> 
</form>

Step 3.6 Add the following function to your Notes-controller (in /app/controllers/notes_controller.php)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public function edit($id = null)
{
   if (empty($this->data['Note']))
   {
       $this->Note->id = $id;
       $this->data = $this->Note->read();
   }
   else
   {
       if($this->Note->save($this->data['Note']))
       {
            $this->flash('Your note has been updated.','/notes/');
       }
   }
}

Deleting an existing note

Step 3.7 Add the following function to your Notes-controller (in /app/controllers/notes_controller.php)

1
2
3
4
5
6
7
8
function delete($id) 
{ 
   if ($this->Note->del($id)) 
   { 
	   $this->Session->setFlash('The note with id: '.$id.' has been deleted.');
	   $this->redirect('/notes');
   } 
}

Demo

The end result after you finished this tutorial: check demo!

Additional features

See part 2 of this tutorial next week to see how:

  • you can add rules to the notes input form fields
  • you can clean the input of your notes form
  • you can use an other than the default layout for your notes application.

Do let me know if you bump into errors.. :) and I’d like it if you let me know if you liked or used this article.

Credits – Original tutorial details

Title: The CakePHP Framework: Your First Bite
Author: Fabio Cevasco
Link: http://www.sitepoint.com/article/application-development-cakephp