1. Create a controller action
Create a controller action used to process comment form submissions. This is a very simple (and dumb) example - enhance as required:
// Controller/CommentsContorller.php
class CommentsController extends AppController {
public $components = array('RequestHandler');
public function add() {
$return = false;
if ($this->request->data) {
$return = $this->Comment->save($this->request->data);
}
if ($this->RequestHandler->isAjax()) {
// return error or result as json
}
// fallback in case of direct access
$this->redirect($this->referer());
}
}
2. Create a comment form
Create a comment form, since you mention in the question using bootstrap modals, wrap the form in appropriate markup:
// View/Elements/comment_form.ctp
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Add a comment
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<?php
echo $this->Form->create('Comment', array('url' => '/comments/add/'));
echo $this->Form->inputs(array(
'comment',
'author'
));
echo $this->Form->submit('add comment');
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
3. Include it in the relevant view file
With the element created, just include it somewhere appropriate, such as at the end of the posts index:
// View/Posts/index.ctp
...
echo $this->element('comment_form');
4. Submit by javascript
This step is optional.
With the above working the comment form should show up (via javascript) when clicking add comment
but since it's a normal form it will be a normal http request upon submission. The comment form already works, don't change it, but most likely you'll want to add a form submission handler so that the form is submitted by ajax. In this way the user is not redirected away from the page.
Something like:
$('form#CommentAdd').submit(function(e) {
e.preventDefault();
$.post(
$(this).attr('href'),
$(this).serialize(),
function(result) {
...
$('#myModal').modal('hide');
}
);
});