Wednesday, November 11, 2009

CakePHP - Adding Records to a Database Table

We have started creating our first CakePHP based application here.
Now to add a record to database table 'posts', I'll define add() function in the class PostsController (in 'app/controllers/posts_controller.php file).
Steps needed:
1. Open posts_controller.php file
2. Add following line of codes below index() function.


function add() {
 if (!empty($this->data)) {
  if ($this->Post->save($this->data)) {
   $this->Session->setFlash('Your post has been saved.');
   $this->redirect(array('action' => 'index'));
   }
}


Note:
First of all, the function checks, if submitted data is empty or not ( if (!empty($this->data)). $this->data contains the form submitted data.
Next, if there is some form data, we are telling Cake (short-form of CakePHP) to save it. ( $this->Post->save($this->data)  ).  '$this->Post' refers to Post model and  'save' method has already been pre-defined in Cake. So, you do not have to write them again. Thus the statement $this->Post->save($this->data) accepts all form data and save it to Post table. Note further, we did not fire up any SQL INSERT Statement to save our records.

$this->Session->setFlash('Your post has been saved.') statement generates a message and displays that message on screen.

 $this->redirect(array('action' => 'index')); statement redirects the user to the index() action for the controller. As such, you can redirect them to any page you like.

So, this is what our Controller does.

Now the view part. We need to create a form to add records.
To do so,
1. Create a new blank file (using any text editor).
2. Type the following code


<h1>Add Post</h1>
<?php
echo $form->create('Post');
echo $form->input('title');
echo $form->input('body', array('rows' => '3'));
echo $form->end('Save Post');
?>

3. Save the file as 'app/views/posts/add.ctp'
4. And you are done.

Note:
1. $form->create('Post'); tells Cake to create a new form and Cake creates following lines of code on the fly: <form id="PostAddForm" method="post" action="/posts/add">
2. $form->input('title');  tells Cake to create an input box for title field.
3. $form->input('body', array('rows' =&gt; '3')); tells Cake to create another input box (Textarea) with rows="3".
4. $form->end('Save Post'); tells Cake to create the submit button.
5. Here is the generated output with all default divs Cake has gladly added for you.

<form id="PostAddForm" method="post" action="/posts/add">
<fieldset style="display:none;">
<input type="hidden" name="_method" value="POST" />
</fieldset>
<div class="input text">
<label for="PostTitle">Title</label><input name="data[Post][title]" type="text" maxlength="50" value=" " id="PostTitle" /></div>
<div class="input textarea"><label for="PostBody">Body</label><textarea name="data[Post][body]" cols="30" rows="3" id="PostBody" ></textarea></div>
<div class="submit"><input type="submit" value="Save Post" /></div>
</form>


To access this page, type the following in your address bar:

http://caketest.local/posts/add

And here is a screenshot of my new Post Form
Now I can create a new blog post easily.
In my next step I will enforce some validation rules for this table (A.K.A. Model).


Thanks again.

2 comments:

volopolo said...

is not working:

Add following line of codes below index() function.


function add() {
if (!empty($this->data)) {
if ($this->Post->save($this->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
}


Parse error: syntax error, unexpected T_STRING, expecting '&' or T_VARIABLE in C:\xampp\htdocs\cake\app\controllers\posts_controller.php on line 4

Siddhartha said...

Check line 4 of your posts_controller.php.

It may be due to some invalid characters getting copied.

If you have copy-pasted it, please paste code to a text editor, remove any undesired/garbage characters that sometimes creep into the code block.

As such, it is better to type the code in your posts_controller.php.

It should work.