Ryan
Ryan

Reputation: 480

Commenting system for CakePHP blog tutorial

I'm building off the CakePHP tutorial for the blog engine by adding comments to each post. I am able to add comments by selecting the post that it should be attached to, via a select box. I would like to be able to click an "Add Comment" link within the post and have the association to the post formed programatically. I am unsure how I can pass the post_id to the add method within my comments_controller. The body of my add method is the auto-generated scaffold code. Is it as easy as adding a $postId argument to the add method and write this to the post_id in my comments model? This doesn't feel right though, since I would expect add to be called when my submit button is click on my comments add view.

Thanks all.

EDIT - Added the code that I'm working with currently. It is just the add method in my comments_controller.

function add($postid = null) {             
    if(!empty($this->data) {
         $this->Comment->create();                          
         $this->Comment->post_id = $postid;
         if ($this->Comment->save($this->data)) {
            $this->Session->setFlash(__('The Comment has been saved', true));
            $this->redirect(array('action' => 'index'));
         } else {
             $this->Session->setFlash(__('The Comment could not be saved. Please, 
                                          try again.', true));
         }
    }   
    $this->set('post_id', $postid);     
    print_r($postid);
}

Upvotes: 2

Views: 3445

Answers (2)

Sergei
Sergei

Reputation: 2757

function add($postid = null) {             
    if(!empty($this->data) {
         $this->Comment->create();                          
         $this->data['Comment']['post_id'] = $postid; // see how it needs to be?
         ...then save the data...

Upvotes: 4

David Yell
David Yell

Reputation: 11855

Create your link at the bottom of your blog post as,

<?php echo $html->link('Add Comment', array('controller'=>'Comments','action'=>'add',$post->id)) ?>

Then you can, in your Comments controller's Add method,

function add($postid){
  $this->data->Comment->post_id = $postid;
  $this->data->Save();
}

Similar to this would do you just fine I'd say. Then your url would be example.com/comments/add/3 Double check the code though, as it's first thing in the morning and we've run out of milk, so I have had no coffee! ;)

Upvotes: 0

Related Questions