Friday, 15 August 2014

CakePHP - Edit a Record in Database

So, the keen readers may guess what we need to do to edit a record in our 'posts' table.
Step:
1. Open posts_controller.php (found under '/app/controllers' folder).
2. Copy-paster the function edit() to edit record.


function edit($id = null) 
{   $this->Post->id = $id; 
  if (empty($this->data)) { 
  $this->data = $this->Post->read(); 
}
 else {  
if ($this->Post->save($this->data)) {

   $this->Session->setFlash('Your post has been updated.');
   $this->redirect(array('action' => 'index')); 
  }  
}  


}
As such, this function edit() is self-explanatory. If you read it carefully, the function edit() expects '$id' value.
$this=>data contains form submitted data. If it is empty ($this=>data will obviously be empty the first time you try to edit a record), the function $this->Post->read() reads the record from database and stores it at $this->data variable to display the same via edit form. If some data has been submitted, the function $this->Post->save($this->data); tries to save that data by updating the respective record.

Now we need to create a form (Cake calls it 'view') to edit record.
Step:
1. Create a new file.
2. Copy-paste following code:
<h1>Edit Post</h1>
<?php  
echo $form->create('Post', array('action' => 'edit'));  
echo $form->input('title');  
echo $form->input('body', array('rows' => '3'));  
echo $form->input('id', array('type'=>'hidden'));   
echo $form->end('Save Post');  
?>
3. Save this file as 'app/views/posts/edit.ctp'

Now we need to add a link to our index.ctp file to display edit option.

Step:
1. Open index.ctp (found under '/app/views/posts' folder)
2. Add the following line just below the line we have added to show 'delete' option.
<?php echo $html->link('Edit', array('action'=>'edit', 'id'=>$post['Post']['id']));?>
3. Save that file.

Now point your browser to:
http://caketest.local/posts

You can see the 'Edit' option.
Now if you follow 'Edit' link, you can see the form with respective record.
Here is a screenshot:

  

7 comments:

  1. I am following your blog from the beginning, it was so distinct & I had a chance to collect conglomeration of information that helps me a lot to improvise myself.
    Regards,
    PHP Course in Chennai|PHP Training Chennai

    ReplyDelete
  2. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

    Best Java Training Institute Chennai


    Amazon Web Services Training in Chennai

    ReplyDelete
  3. Hello! Someone in my Facebook group shared this website with us, so I came to give it a look. I’m enjoying the information. I’m bookmarking and will be tweeting this to my followers! Wonderful blog and amazing design and style.
    fire and safety course in chennai

    ReplyDelete